// 全局变量，用于跟踪模态框是否已创建
let globalModalCreated = false;
// 全局变量，存储当前用户的公司ID
let currentCompanyId = null;

// 创建模态框函数
function createGlobalModal() {
    if (globalModalCreated) {
        return; // 如果已经创建过，直接返回
    }
    
    const modalHTML = `
        <div id="application-modal" class="modal">
            <div class="modal-content">
                <span class="close-modal">&times;</span>
                <h3 class="modal-title">申请详情</h3>
                <div id="modal-body"></div>
                <div class="modal-footer">
                    <button class="btn btn-primary" id="modal-confirm-btn">确定</button>
                    <button class="btn btn-danger" id="modal-cancel-btn">取消</button>
                </div>
            </div>
        </div>
    `;
    document.body.insertAdjacentHTML('beforeend', modalHTML);
    
    const modal = document.getElementById('application-modal');
    const closeModal = modal.querySelector('.close-modal');
    const modalCancelBtn = document.getElementById('modal-cancel-btn');
    
    // 关闭模态框
    closeModal.addEventListener('click', function() {
        modal.style.display = 'none';
    });
    
    modalCancelBtn.addEventListener('click', function() {
        modal.style.display = 'none';
    });
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    });
    
    globalModalCreated = true;
    // console.log('全局模态框已创建');
}

document.addEventListener('DOMContentLoaded', function() {
    // 创建全局模态框
    createGlobalModal();
    
    // 初始化各功能模块
    checkJoinCompanyStatus();
    fetchCurrentUserInfo();
    checkApplicationStatus();
    initEmployeeApplications();
    initTaskManagement();
    initClockSettings();
    initClockRecords();
    initEmployeePerformance();
    initAnnouncementManagement();
    initEmployeeModals(); // 初始化员工模态框
    loadEmployees(); // 加载员工列表
    initEmployeeSearch(); // 初始化员工搜索功能
    
    // 初始化离职申请管理
    initResignationManagement();
});

// 初始化入职申请管理
function initEmployeeApplications() {
    // 初始加载入职申请
    loadEmployeeApplications(0); // 默认加载待审核的申请
    
    // 绑定筛选按钮事件
    const filterBtns = document.querySelectorAll('#employee-applications .filter-btn');
    filterBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            // 移除所有按钮的active类
            filterBtns.forEach(b => b.classList.remove('active'));
            // 为当前点击的按钮添加active类
            this.classList.add('active');
            
            // 获取状态值
            const status = this.getAttribute('data-status');
            // 加载对应状态的申请
            loadEmployeeApplications(status);
        });
    });
    
    // 绑定刷新按钮事件
    const refreshBtn = document.getElementById('refresh-applications-btn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', function() {
            const activeFilterBtn = document.querySelector('#employee-applications .filter-btn.active');
            const status = activeFilterBtn ? activeFilterBtn.getAttribute('data-status') : '0';
            loadEmployeeApplications(status);
        });
    }
}

// 初始化公告管理
function initAnnouncementManagement() {
    // 加载公告列表
    loadAnnouncements();
    
    // 绑定新增公告按钮事件
    const addAnnouncementBtn = document.getElementById('add-announcement-btn');
    if (addAnnouncementBtn) {
        addAnnouncementBtn.addEventListener('click', function() {
            showAnnouncementForm();
        });
    }
    
    // 绑定刷新公告按钮事件
    const refreshAnnouncementsBtn = document.getElementById('refresh-announcements-btn');
    if (refreshAnnouncementsBtn) {
        refreshAnnouncementsBtn.addEventListener('click', function() {
            loadAnnouncements();
        });
    }
}

// 初始化离职申请管理
function initResignationManagement() {
    const refreshBtn = document.getElementById('refresh-resignations-btn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', function() {
            loadResignations();
        });
    }
    
    // 初始加载离职申请
    loadResignations();
}

// 加载离职申请列表
function loadResignations() {
    const container = document.getElementById('resignation-applications-container');
    if (!container) return;
    
    container.innerHTML = '<div class="loading">加载中...</div>';
    
    fetch('getResignations')
    .then(response => response.json())
    .then(data => {
        if (data.success && data.data) {
            if (data.data.length > 0) {
                displayResignations(data.data, container);
            } else {
                container.innerHTML = '<div class="no-data">暂无离职申请</div>';
            }
        } else {
            container.innerHTML = `<div class="alert alert-warning">${data.message || '无法加载离职申请'}</div>`;
        }
    })
    .catch(error => {
        // console.error('加载离职申请出错:', error);
        container.innerHTML = '<div class="alert alert-danger">加载离职申请时出错，请稍后再试</div>';
    });
}

// 显示离职申请列表
function displayResignations(resignations, container) {
    if (!resignations || resignations.length === 0) {
        container.innerHTML = '<div class="no-data">暂无离职申请</div>';
        return;
    }
    
    let html = '<div class="resignation-list">';
    
    html += `
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>员工姓名</th>
                        <th>员工编号</th>
                        <th>职位</th>
                        <th>离职原因</th>
                        <th>申请时间</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    resignations.forEach(resignation => {
        // 确定状态文本
        let statusText = '';
        switch(resignation.status) {
            case 0:
                statusText = '<span style="color: #f39c12;">待入职审核</span>';
                break;
            case 1:
                statusText = '<span style="color: #2ecc71;">在职</span>';
                break;
            case 2:
                statusText = '<span style="color: #e74c3c;">已拒绝入职</span>';
                break;
            case 3:
                statusText = '<span style="color: #f39c12;">待审核离职</span>';
                break;
            case 4:
                statusText = '<span style="color: #3498db;">已离职</span>';
                break;
            default:
                statusText = '<span style="color: #7f8c8d;">未知状态</span>';
        }
        
        html += `
            <tr>
                <td>${resignation.userName || ''}</td>
                <td>${resignation.employeeNumber || ''}</td>
                <td>${resignation.position || ''}</td>
                <td>${resignation.resignationReason || ''}</td>
                <td>${formatDateTime(resignation.resignationTime) || ''}</td>
                <td>${statusText}</td>
                <td>
                    <button class="btn btn-sm btn-success approve-resignation-btn" data-id="${resignation.id}">批准离职</button>
                    <button class="btn btn-sm btn-danger reject-resignation-btn" data-id="${resignation.id}">拒绝离职</button>
                </td>
            </tr>
        `;
    });
    
    html += `
                </tbody>
            </table>
                </div>
            </div>
        `;
    
    container.innerHTML = html;
    
    // 绑定批准离职按钮事件
    const approveButtons = container.querySelectorAll('.approve-resignation-btn');
    approveButtons.forEach(button => {
        button.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            if (confirm('确定批准该员工的离职申请吗？批准后员工将离开公司。')) {
                reviewResignation(id, 'approve');
            }
        });
    });
    
    // 绑定拒绝离职按钮事件
    const rejectButtons = container.querySelectorAll('.reject-resignation-btn');
    rejectButtons.forEach(button => {
        button.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            if (confirm('确定拒绝该员工的离职申请吗？员工将继续留在公司。')) {
                reviewResignation(id, 'reject');
            }
        });
    });
}

// 处理离职申请
function reviewResignation(id, action) {
    const formData = new URLSearchParams();
    formData.append('id', id);
    formData.append('action', action);
    
    fetch('reviewResignation', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message || '操作成功');
            loadResignations(); // 重新加载离职申请列表
        } else {
            alert(data.message || '操作失败，请稍后再试');
        }
    })
    .catch(error => {
        // console.error('处理离职申请出错:', error);
        alert('系统错误，请稍后再试');
    });
}

// 检查加入公司状态
function checkJoinCompanyStatus() {
    const submenuFeatures = document.querySelectorAll('.submenu-feature');
    
    fetch('checkJoinCompanyStatus')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (data.inCompany) {
                // 用户已加入公司，启用所有功能
                enableFeatures();
            } else {
                // 用户未加入公司，禁用功能
                disableFeatures();
            }
        } else {
            // console.error('获取加入公司状态失败:', data.message);
        }
    })
    .catch(error => {
        // console.error('获取加入公司状态出错:', error);
    });
}

function enableFeatures() {
    const submenuFeatures = document.querySelectorAll('.submenu-feature');
    submenuFeatures.forEach(item => {
        item.classList.remove('disabled');
    });
}

function disableFeatures() {
    const submenuFeatures = document.querySelectorAll('.submenu-feature');
    submenuFeatures.forEach(item => {
        item.classList.add('disabled');
    });
}

// 检查系统使用申请状态
function checkApplicationStatus() {
    fetch('checkApplicationStatus')
    .then(response => response.json())
    .then(data => {
        const statusContainer = document.getElementById('application-status-container');
        const formContainer = document.getElementById('application-form-container');
        
        if (data.success) {
            const status = data.status;
            if (status === -1) {
                // 未申请
                statusContainer.innerHTML = `
                    <div class="status-box status-none">
                        您尚未提交系统使用申请
                    </div>
                `;
                displayApplicationForm(formContainer);
            } else if (status === 0) {
                // 审核中
                statusContainer.innerHTML = `
                    <div class="status-box status-pending">
                        您的系统使用申请正在审核中
                    </div>
                `;
                displayApplicationInfo(formContainer, data.application);
            } else if (status === 1) {
                // 已通过
                statusContainer.innerHTML = `
                    <div class="status-box status-approved">
                        您的系统使用申请已通过
                    </div>
                `;
                
                // 显示申请信息
                displayApplicationInfo(formContainer, data.application);
                
                // 如果有公司ID，直接添加到申请信息中
                if (data.companyId) {
                    const applicationInfo = formContainer.querySelector('.application-info');
                    if (applicationInfo) {
                        // 找到审核时间的段落
                        const updateTimeParagraph = applicationInfo.querySelector('p:nth-child(3)');
                        if (updateTimeParagraph) {
                            // 先添加公司名称
                            const companyNameParagraph = document.createElement('p');
                            companyNameParagraph.innerHTML = `<strong>公司名称：</strong>${data.application.companyName || '未知'}`;
                            updateTimeParagraph.insertAdjacentElement('afterend', companyNameParagraph);
                            
                            // 再添加公司ID
                            const companyIdParagraph = document.createElement('p');
                            companyIdParagraph.innerHTML = `<strong>公司ID：</strong>${data.companyId}`;
                            companyNameParagraph.insertAdjacentElement('afterend', companyIdParagraph);
                        }
                    }
                }
            } else if (status === 2) {
                // 已拒绝
                statusContainer.innerHTML = `
                    <div class="status-box status-rejected">
                        您的系统使用申请已被拒绝
                    </div>
                `;
                displayApplicationInfo(formContainer, data.application);
                
                // 添加重新申请按钮
                formContainer.innerHTML += `
                    <div style="margin-top: 20px;">
                        <button id="reapply-btn" class="btn btn-primary">重新申请</button>
                    </div>
                `;
                
                document.getElementById('reapply-btn').addEventListener('click', function() {
                    displayApplicationForm(formContainer);
                });
            }
        } else {
            statusContainer.innerHTML = `
                <div class="alert alert-danger">
                    ${data.message || '获取申请状态失败，请刷新页面重试'}
                </div>
            `;
        }
    })
    .catch(error => {
        // console.error('检查申请状态出错:', error);
    });
}

// 显示申请表单
function displayApplicationForm(container) {
    container.innerHTML = `
        <form id="application-form" action="submitApplication" method="post">
            <div class="form-group">
                <label for="reason">申请原因</label>
                <textarea class="form-control" id="reason" name="reason" required placeholder="请描述您为什么需要使用系统..."></textarea>
            </div>
            <button type="submit" class="btn btn-primary">提交申请</button>
        </form>
    `;
}

// 显示申请信息
function displayApplicationInfo(container, application) {
    if (!application) {
        container.innerHTML = `
            <div class="alert alert-warning">
                无法获取申请信息
            </div>
        `;
        return;
    }
    
    let html = `
        <div class="application-info">
            <p><strong>申请时间：</strong>${formatDateTime(application.createTime)}</p>
            <p><strong>申请原因：</strong>${application.reason || '无'}</p>
    `;
    
    if (application.status === 0) {
        html += `
            <div class="alert alert-warning">
                您的申请正在审核中，请耐心等待
            </div>
        `;
    } else if (application.status === 1) {
        html += `
            <p><strong>审核时间：</strong>${formatDateTime(application.updateTime)}</p>
        `;
        
        html += `
            <div class="alert alert-success">
                您的申请已通过，可以使用系统的所有功能
            </div>
        `;
    } else if (application.status === 2) {
        html += `
            <p><strong>拒绝原因：</strong>${application.rejectReason || '无'}</p>
            <p><strong>拒绝时间：</strong>${formatDateTime(application.updateTime)}</p>
            <div class="alert alert-danger">
                您的申请被拒绝，请查看拒绝原因并重新申请
            </div>
        `;
    }
    
    html += '</div>';
    container.innerHTML = html;
}

function loadEmployeeApplications(status) {
    // 显示加载中
    const container = document.getElementById('employee-applications-container');
    container.innerHTML = '<div class="loading">加载中...</div>';
    
    // 构建URL
    let url = 'getEmployeeApplications';
    if (status && status !== '-1') {
        url += `?status=${status}`;
    }
    
    // 获取入职申请
    fetch(url)
    .then(response => response.json())
    .then(data => {
        if (!data.success) {
            container.innerHTML = `
                <div class="alert alert-danger">
                    ${data.message || '获取入职申请失败，请刷新页面重试'}
                </div>
            `;
            return;
        }
        
        const applications = data.applications;
        const company = data.company;
        
        if (!applications || applications.length === 0) {
            container.innerHTML = `
                <div class="alert alert-info">
                    暂无入职申请记录
                </div>
            `;
            return;
        }
        
        // 渲染申请列表
        let html = `
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>申请人</th>
                            <th>联系电话</th>
                            <th>申请时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
        `;
        
        applications.forEach(app => {
            let statusText = '';
            let actionBtns = '';
            
            switch(app.status) {
                case 0:
                    statusText = '<span style="color: #f39c12;">审核中</span>';
                    actionBtns = `
                        <button class="action-btn approve-btn" data-id="${app.id}">通过</button>
                        <button class="action-btn reject-btn" data-id="${app.id}">拒绝</button>
                        <button class="action-btn view-btn" data-id="${app.id}">查看</button>
                    `;
                    break;
                case 1:
                    statusText = '<span style="color: #2ecc71;">已通过</span>';
                    actionBtns = `
                        <button class="action-btn view-btn" data-id="${app.id}">查看</button>
                    `;
                    break;
                case 2:
                    statusText = '<span style="color: #e74c3c;">已拒绝</span>';
                    actionBtns = `
                        <button class="action-btn view-btn" data-id="${app.id}">查看</button>
                    `;
                    break;
                default:
                    statusText = '<span style="color: #7f8c8d;">未知状态</span>';
                    actionBtns = `
                        <button class="action-btn view-btn" data-id="${app.id}">查看</button>
                    `;
            }
            
            html += `
                <tr>
                    <td>${app.userName}</td>
                    <td>${app.userPhone}</td>
                    <td>${formatDateTime(app.createTime)}</td>
                    <td>${statusText}</td>
                    <td>${actionBtns}</td>
                </tr>
            `;
        });
        
        html += `
                    </tbody>
                </table>
            </div>
        `;
        
        container.innerHTML = html;
        
        // 确保每次加载申请列表后都绑定按钮事件
        bindActionButtons();
    })
    .catch(error => {
        // console.error('获取入职申请出错:', error);
        container.innerHTML = `
            <div class="alert alert-danger">
                系统错误，请刷新页面重试
            </div>
        `;
    });
}

function bindActionButtons() {
    // 绑定查看按钮
    const viewBtns = document.querySelectorAll('.view-btn');
    viewBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const applicationId = this.getAttribute('data-id');
            showApplicationDetails(applicationId);
        });
    });
    
    // 绑定通过按钮
    const approveBtns = document.querySelectorAll('.approve-btn');
    approveBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const applicationId = this.getAttribute('data-id');
            showApproveConfirmation(applicationId);
        });
    });
    
    // 绑定拒绝按钮
    const rejectBtns = document.querySelectorAll('.reject-btn');
    rejectBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const applicationId = this.getAttribute('data-id');
            showRejectConfirmation(applicationId);
        });
    });
}

function showApplicationDetails(applicationId) {
    const modal = document.getElementById('application-modal');
    const modalBody = document.getElementById('modal-body');
    const modalConfirmBtn = document.getElementById('modal-confirm-btn');
    const modalCancelBtn = document.getElementById('modal-cancel-btn');
    
    // 显示加载中
    modalBody.innerHTML = '<div class="loading">加载中...</div>';
    
    // 隐藏按钮
    modalConfirmBtn.style.display = 'none';
    modalCancelBtn.style.display = 'none';
    
    // 显示模态框
    modal.style.display = 'block';
    
    // 获取申请详情
    fetch(`getEmployeeApplications?id=${applicationId}`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 直接使用返回的单个申请，而不是从列表中查找
            const application = data.application;
            
            if (!application) {
                modalBody.innerHTML = `
                    <div class="alert alert-danger">
                        找不到指定的申请记录
                    </div>
                `;
                modalCancelBtn.style.display = 'inline-block';
                modalCancelBtn.textContent = '关闭';
                return;
            }
            
            let statusText = '';
            let statusClass = '';
            
            switch(application.status) {
                case 0:
                    statusText = '待审核';
                    statusClass = 'status-pending';
                    break;
                case 1:
                    statusText = '已通过';
                    statusClass = 'status-approved';
                    break;
                case 2:
                    statusText = '已拒绝';
                    statusClass = 'status-rejected';
                    break;
                default:
                    statusText = '未知状态';
            }
            
            let html = `
                <div class="application-info">
                    <div class="status-badge ${statusClass}">${statusText}</div>
                    <h4>申请详情</h4>
                    <div class="detail-item">
                        <span class="detail-label">申请人：</span>
                        <span class="detail-value">${application.userName}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">联系电话：</span>
                        <span class="detail-value">${application.userPhone}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">申请时间：</span>
                        <span class="detail-value">${formatDateTime(application.createTime)}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">申请理由：</span>
                        <span class="detail-value">${application.reason || '无'}</span>
                    </div>
            `;
            
            if (application.status === 1) {
                html += `
                    <div class="detail-item">
                        <span class="detail-label">员工编号：</span>
                        <span class="detail-value">${application.employeeNumber || '未分配'}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">职位：</span>
                        <span class="detail-value">${application.position || '未设置'}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">基础薪资：</span>
                        <span class="detail-value">${application.baseSalary ? application.baseSalary + ' 元' : '未设置'}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">通过时间：</span>
                        <span class="detail-value">${formatDateTime(application.updateTime)}</span>
                    </div>
                `;
            } else if (application.status === 2) {
                html += `
                    <div class="detail-item">
                        <span class="detail-label">拒绝原因：</span>
                        <span class="detail-value">${application.rejectReason || '无'}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">拒绝时间：</span>
                        <span class="detail-value">${formatDateTime(application.updateTime)}</span>
                    </div>
                `;
            }
            
            html += '</div>';
            
            if (application.status === 0) {
                html += `
                    <div class="action-buttons mt-3">
                        <button class="btn btn-success approve-btn" data-id="${application.id}">通过申请</button>
                        <button class="btn btn-danger reject-btn" data-id="${application.id}">拒绝申请</button>
                    </div>
                `;
            }
            
            modalBody.innerHTML = html;
            
            // 绑定操作按钮事件
            if (application.status === 0) {
                const approveBtn = modalBody.querySelector('.approve-btn');
                const rejectBtn = modalBody.querySelector('.reject-btn');
                
                approveBtn.addEventListener('click', function() {
                    modal.style.display = 'none';
                    showApproveConfirmation(application.id);
                });
                
                rejectBtn.addEventListener('click', function() {
                    modal.style.display = 'none';
                    showRejectConfirmation(application.id);
                });
            }
            
            // 显示关闭按钮
            modalCancelBtn.style.display = 'inline-block';
            modalCancelBtn.textContent = '关闭';
        } else {
            modalBody.innerHTML = `
                <div class="alert alert-danger">
                    ${data.message || '获取申请详情失败'}
                </div>
            `;
            
            // 显示关闭按钮
            modalCancelBtn.style.display = 'inline-block';
            modalCancelBtn.textContent = '关闭';
        }
    })
    .catch(error => {
        // console.error('获取申请详情出错:', error);
        modalBody.innerHTML = `
            <div class="alert alert-danger">
                系统错误，请稍后再试
            </div>
        `;
        
        // 显示关闭按钮
        modalCancelBtn.style.display = 'inline-block';
        modalCancelBtn.textContent = '关闭';
    });
}

function showApproveConfirmation(applicationId) {
    const modal = document.getElementById('application-modal');
    const modalBody = document.getElementById('modal-body');
    const modalConfirmBtn = document.getElementById('modal-confirm-btn');
    const modalCancelBtn = document.getElementById('modal-cancel-btn');
    
    modalBody.innerHTML = `
        <p>请为该员工设置职位和基础薪资：</p>
        <div class="form-group">
            <label for="position">职位：</label>
            <input type="text" class="form-control" id="position" placeholder="请输入职位..." required>
            <small class="text-danger" id="position-error" style="display:none;">不能将员工职位设置为"负责人"</small>
        </div>
        <div class="form-group">
            <label for="baseSalary">基础薪资（元）：</label>
            <input type="number" class="form-control" id="baseSalary" placeholder="请输入基础薪资..." min="0" step="0.01" required>
        </div>
        <p class="mt-2">通过后将为该员工分配员工编号。</p>
    `;
    
    // 添加职位输入验证
    const positionInput = document.getElementById('position');
    const positionError = document.getElementById('position-error');
    
    positionInput.addEventListener('input', function() {
        if (this.value.trim() === '负责人') {
            positionError.style.display = 'block';
            modalConfirmBtn.disabled = true;
        } else {
            positionError.style.display = 'none';
            modalConfirmBtn.disabled = false;
        }
    });
    
    // 显示确认和取消按钮，并确保按钮未被禁用
    modalConfirmBtn.style.display = 'inline-block';
    modalConfirmBtn.disabled = false;
    modalConfirmBtn.textContent = '确认通过';
    
    modalCancelBtn.style.display = 'inline-block';
    modalCancelBtn.disabled = false;
    modalCancelBtn.textContent = '取消';
    
    // 绑定确认按钮事件
    modalConfirmBtn.onclick = function() {
        const position = document.getElementById('position').value.trim();
        const baseSalary = document.getElementById('baseSalary').value.trim();
        
        if (!position) {
            alert('请输入职位');
            return;
        }
        
        if (position === '负责人') {
            alert('不能将员工职位设置为"负责人"');
            return;
        }
        
        if (!baseSalary) {
            alert('请输入基础薪资');
            return;
        }
        
        reviewApplication(applicationId, 1, null, position, baseSalary);
    };
    
    // 显示取消按钮
    modalCancelBtn.style.display = 'inline-block';
    modalCancelBtn.textContent = '取消';
    
    // 显示模态框
    modal.style.display = 'block';
}

function showRejectConfirmation(applicationId) {
    const modal = document.getElementById('application-modal');
    const modalBody = document.getElementById('modal-body');
    const modalConfirmBtn = document.getElementById('modal-confirm-btn');
    const modalCancelBtn = document.getElementById('modal-cancel-btn');
    
    modalBody.innerHTML = `
        <p>确定拒绝此申请吗？</p>
        <div class="form-group">
            <label for="rejectReason">拒绝原因：</label>
            <textarea class="form-control" id="rejectReason" placeholder="请输入拒绝原因..."></textarea>
        </div>
    `;
    
    // 显示确认和取消按钮，并确保按钮未被禁用
    modalConfirmBtn.style.display = 'inline-block';
    modalConfirmBtn.disabled = false;
    modalConfirmBtn.textContent = '确认拒绝';
    
    modalCancelBtn.style.display = 'inline-block';
    modalCancelBtn.disabled = false;
    modalCancelBtn.textContent = '取消';
    
    // 绑定确认按钮事件
    modalConfirmBtn.onclick = function() {
        const rejectReason = document.getElementById('rejectReason').value;
        reviewApplication(applicationId, 2, rejectReason);
    };
    
    // 显示取消按钮
    modalCancelBtn.style.display = 'inline-block';
    modalCancelBtn.textContent = '取消';
    
    // 显示模态框
    modal.style.display = 'block';
}

function reviewApplication(applicationId, status, rejectReason, position, baseSalary) {
    const modal = document.getElementById('application-modal');
    const modalConfirmBtn = document.getElementById('modal-confirm-btn');
    const modalCancelBtn = document.getElementById('modal-cancel-btn');
    
    // 禁用按钮
    modalConfirmBtn.disabled = true;
    modalCancelBtn.disabled = true;
    
    // 构建表单数据
    const formData = new URLSearchParams();
    formData.append('applicationId', applicationId);
    formData.append('status', status);
    if (rejectReason) {
        formData.append('rejectReason', rejectReason);
    }
    if (position) {
        formData.append('position', position);
    }
    if (baseSalary) {
        formData.append('baseSalary', baseSalary);
    }
    
    // 发送审核请求
    fetch('reviewEmployeeApplication', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message || '操作成功');
            
            // 重置按钮状态
            modalConfirmBtn.disabled = false;
            modalCancelBtn.disabled = false;
            
            // 关闭模态框
            modal.style.display = 'none';
            
                          // 重新加载申请列表
              const activeFilterBtn = document.querySelector('.filter-btn.active');
              const status = activeFilterBtn ? activeFilterBtn.getAttribute('data-status') : '-1';
              loadEmployeeApplications(status);
        } else {
            alert(data.message || '操作失败');
            // 恢复按钮
            modalConfirmBtn.disabled = false;
            modalCancelBtn.disabled = false;
        }
    })
    .catch(error => {
        // console.error('审核申请出错:', error);
        alert('系统错误，请稍后再试');
        // 恢复按钮
        modalConfirmBtn.disabled = false;
        modalCancelBtn.disabled = false;
    });
}

function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '未知';
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
}

// 加载公告列表
function loadAnnouncements() {
    const announcementContent = document.getElementById('announcement-content');
    if (!announcementContent) return;
    
    announcementContent.innerHTML = '<div class="loading">加载中...</div>';
    
    fetch('api/announcements')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (data.data && data.data.length > 0) {
                let html = '<div class="announcement-list">';
                data.data.forEach(announcement => {
                    const publishTime = formatDateTime(announcement.publishTime);
                    const updateTime = formatDateTime(announcement.updateTime);
                    const isUpdated = announcement.publishTime !== announcement.updateTime;
                    
                    html += `
                        <div class="announcement-item" data-id="${announcement.id}">
                            <div class="announcement-header">
                                <h3 class="announcement-title">${announcement.title}</h3>
                                <div class="announcement-meta">
                                    <span class="publisher">发布人: ${announcement.publisherName}</span>
                                    <span class="publish-time">发布时间: ${publishTime}</span>
                                    ${isUpdated ? `<span class="update-time">最后更新: ${updateTime}</span>` : ''}
                                </div>
                                <div class="announcement-actions">
                                    <button class="btn btn-sm btn-primary edit-announcement-btn" data-id="${announcement.id}">编辑</button>
                                    <button class="btn btn-sm btn-danger delete-announcement-btn" data-id="${announcement.id}">删除</button>
                                </div>
                            </div>
                            <div class="announcement-content">${announcement.content}</div>
                        </div>
                    `;
                });
                html += '</div>';
                announcementContent.innerHTML = html;
                
                // 绑定编辑和删除按钮事件
                bindAnnouncementActions();
            } else {
                announcementContent.innerHTML = '<div class="alert alert-info">暂无公告，点击"新增公告"按钮创建公告</div>';
            }
        } else {
            announcementContent.innerHTML = `<div class="alert alert-danger">${data.message || '获取公告失败'}</div>`;
        }
    })
    .catch(error => {
        // console.error('获取公告出错:', error);
        announcementContent.innerHTML = '<div class="alert alert-danger">系统错误，请稍后再试</div>';
    });
}

// 绑定公告操作按钮事件
function bindAnnouncementActions() {
    // 绑定编辑按钮
    const editBtns = document.querySelectorAll('.edit-announcement-btn');
    editBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const announcementId = this.getAttribute('data-id');
            editAnnouncement(announcementId);
        });
    });
    
    // 绑定删除按钮
    const deleteBtns = document.querySelectorAll('.delete-announcement-btn');
    deleteBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const announcementId = this.getAttribute('data-id');
            deleteAnnouncement(announcementId);
        });
    });
}

// 显示新增公告表单
function showAnnouncementForm(announcement = null) {
    // 创建简化版本的公告表单
    const isEdit = announcement !== null;
    
    // 创建一个全新的模态框，而不是复用现有的
    const modalId = "announcement-modal-" + Date.now();
    const modalHTML = `
        <div id="${modalId}" class="modal" style="display:block;">
            <div class="modal-content">
                <span class="close-modal">&times;</span>
                <h3 class="modal-title">${isEdit ? '编辑公告' : '新增公告'}</h3>
                <div class="modal-body">
                    <form id="announcement-form-${modalId}">
                        ${isEdit ? `<input type="hidden" id="announcement-id-${modalId}" value="${announcement.id}">` : ''}
                        <div class="form-group">
                            <label for="announcement-title-${modalId}">公告标题</label>
                            <input type="text" class="form-control" id="announcement-title-${modalId}" placeholder="请输入公告标题" value="${isEdit ? announcement.title : ''}">
                        </div>
                        <div class="form-group">
                            <label for="announcement-content-${modalId}">公告内容</label>
                            <textarea class="form-control" id="announcement-content-${modalId}" rows="6" placeholder="请输入公告内容">${isEdit ? announcement.content : ''}</textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-primary" id="modal-confirm-btn-${modalId}">${isEdit ? '更新' : '发布'}</button>
                    <button class="btn btn-danger" id="modal-cancel-btn-${modalId}">取消</button>
                </div>
            </div>
        </div>
    `;
    
    // 添加到页面
    document.body.insertAdjacentHTML('beforeend', modalHTML);
    
    // 获取元素
    const modal = document.getElementById(modalId);
    const closeBtn = modal.querySelector('.close-modal');
    const confirmBtn = document.getElementById(`modal-confirm-btn-${modalId}`);
    const cancelBtn = document.getElementById(`modal-cancel-btn-${modalId}`);
    
    // 绑定关闭事件
    function closeModal() {
        document.body.removeChild(modal);
    }
    
    closeBtn.onclick = closeModal;
    cancelBtn.onclick = closeModal;
    
    // 点击外部关闭
    window.addEventListener('click', function(event) {
        if (event.target === modal) {
            closeModal();
        }
    });
    
    // 绑定确认按钮事件
    confirmBtn.onclick = function() {
        // 获取表单元素
        const titleElement = document.getElementById(`announcement-title-${modalId}`);
        const contentElement = document.getElementById(`announcement-content-${modalId}`);
        
        if (!titleElement || !contentElement) {
            // console.error('找不到表单元素');
            alert('系统错误，请刷新页面后重试');
            return;
        }
        
        const title = titleElement.value.trim();
        const content = contentElement.value.trim();
        
        // console.log('获取到的表单数据:', {title, content});
        
        if (!title || !content) {
            alert('标题和内容不能为空');
            return;
        }
        
        if (isEdit) {
            // 更新公告
            const idElement = document.getElementById(`announcement-id-${modalId}`);
            if (!idElement) {
                // console.error('找不到ID元素');
                alert('系统错误，请刷新页面后重试');
                return;
            }
            const id = idElement.value;
            updateAnnouncement(id, title, content);
        } else {
            // 添加公告
            addAnnouncement(title, content);
        }
        
        // 关闭并移除模态框
        closeModal();
    };
}

// 添加公告
function addAnnouncement(title, content) {
    // 打印要发送的数据，用于调试
    // console.log('发送的数据:', {title: title, content: content});
    
    // 添加更多日志，显示当前用户信息
    // console.log('当前用户信息:', window.currentUser);
    
    fetch('api/manage-announcement', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json;charset=utf-8'
        },
        body: JSON.stringify({
            title: title,
            content: content
        })
    })
    .then(response => {
        // 打印响应状态，用于调试
        // console.log('响应状态:', response.status);
        return response.text().then(text => {
            try {
                // 尝试解析JSON
                // console.log('响应文本:', text);
                return text ? JSON.parse(text) : {};
            } catch (e) {
                // console.error('解析JSON出错:', e);
                // console.error('原姻响应文本:', text);
                return { success: false, message: '解析响应失败: ' + e.message };
            }
        });
    })
    .then(data => {
        // console.log('处理后的响应数据:', data);
        if (data.success) {
            alert('公告发布成功');
            loadAnnouncements();
        } else {
            alert(data.message || '公告发布失败');
        }
    })
    .catch(error => {
        // console.error('发布公告出错:', error);
        alert('系统错误，请稍后再试: ' + error.message);
    });
}

// 编辑公告
function editAnnouncement(announcementId) {
    // 获取公告详情
    fetch(`api/manage-announcement?id=${announcementId}`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAnnouncementForm(data.data);
        } else {
            alert(data.message || '获取公告详情失败');
        }
    })
    .catch(error => {
        // console.error('获取公告详情出错:', error);
        alert('系统错误，请稍后再试');
    });
}

// 更新公告
function updateAnnouncement(id, title, content) {
    // 打印要发送的数据，用于调试
    // console.log('发送的更新数据:', {id: id, title: title, content: content});
    
    fetch('api/manage-announcement', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json;charset=utf-8'
        },
        body: JSON.stringify({
            id: id,
            title: title,
            content: content
        })
    })
    .then(response => {
        // 打印响应状态，用于调试
        // console.log('响应状态:', response.status);
        return response.text().then(text => {
            try {
                // 尝试解析JSON
                // console.log('响应文本:', text);
                return text ? JSON.parse(text) : {};
            } catch (e) {
                // console.error('解析JSON出错:', e);
                return { success: false, message: '解析响应失败' };
            }
        });
    })
    .then(data => {
        if (data.success) {
            alert('公告更新成功');
            loadAnnouncements();
        } else {
            alert(data.message || '公告更新失败');
        }
    })
    .catch(error => {
        // console.error('更新公告出错:', error);
        alert('系统错误，请稍后再试');
    });
}

// 删除公告
function deleteAnnouncement(announcementId) {
    if (!confirm('确定要删除该公告吗？此操作不可恢复。')) {
        return;
    }
    
    fetch(`api/manage-announcement?id=${announcementId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('公告删除成功');
            loadAnnouncements();
        } else {
            alert(data.message || '公告删除失败');
        }
    })
    .catch(error => {
        // console.error('删除公告出错:', error);
        alert('系统错误，请稍后再试');
    });
}

// 初始化员工搜索功能
function initEmployeeSearch() {
    const searchInput = document.getElementById('employee-search');
    const searchBtn = document.getElementById('search-employee-btn');
    const resetBtn = document.getElementById('reset-employee-search-btn');
    
    if (!searchInput || !searchBtn || !resetBtn) {
        // console.error('员工搜索相关元素未找到');
        return;
    }
    
    // 搜索按钮点击事件
    searchBtn.addEventListener('click', function() {
        const keyword = searchInput.value.trim();
        loadEmployees(keyword);
    });
    
    // 重置按钮点击事件
    resetBtn.addEventListener('click', function() {
        searchInput.value = '';
        loadEmployees();
    });
    
    // 搜索框回车事件
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            const keyword = searchInput.value.trim();
            loadEmployees(keyword);
        }
    });
}

// 加载员工列表
function loadEmployees(keyword) {
    const employeesContainer = document.getElementById('employees-container');
    if (!employeesContainer) return;
    
    employeesContainer.innerHTML = '<div class="loading">加载中...</div>';
    
    let url = 'getEmployees';
    if (keyword) {
        url += `?keyword=${encodeURIComponent(keyword)}`;
    }
    
    // console.log('开始加载员工列表，请求URL:', url);
    
    fetch(url)
        .then(response => {
            // console.log('员工列表API响应状态:', response.status);
            return response.json();
        })
        .then(data => {
            // console.log('员工列表API响应数据:', data);
            if (data.success) {
                if (data.employees && data.employees.length > 0) {
                    // console.log(`成功加载${data.employees.length}名员工`);
                    let html = '<div class="table-responsive"><table class="table"><thead><tr>' +
                        '<th>员工ID</th>' +
                        '<th>姓名</th>' +
                        '<th>电话</th>' +
                        '<th>职位</th>' +
                        '<th>操作</th>' +
                        '</tr></thead><tbody>';
                    
                    data.employees.forEach(employee => {
                        html += `
                            <tr>
                                <td>${employee.id}</td>
                                <td>${employee.userName}</td>
                                <td>${employee.userPhone}</td>
                                <td>${employee.position || '未设置'}</td>
                                <td>
                                    <button class="btn btn-sm btn-info view-employee" data-id="${employee.id}">查看详情</button>
                                </td>
                            </tr>
                        `;
                    });
                    
                    html += '</tbody></table></div>';
                    employeesContainer.innerHTML = html;
                    
                    // 绑定查看详情按钮事件
                    bindViewEmployeeButtons();
                } else {
                    // console.log('没有找到员工数据');
                    employeesContainer.innerHTML = '<div class="alert alert-info">暂无员工信息</div>';
                }
            } else {
                // console.error('获取员工列表失败:', data.message);
                employeesContainer.innerHTML = `<div class="alert alert-danger">${data.message || '获取员工列表失败'}</div>`;
            }
        })
        .catch(error => {
            // console.error('获取员工列表出错:', error);
            employeesContainer.innerHTML = `
                <div class="alert alert-danger">
                    <p>加载员工列表失败，请检查网络连接或联系管理员</p>
                    <p>错误详情: ${error.message}</p>
                    <button class="btn btn-primary mt-2" onclick="loadEmployees()">重试</button>
                </div>
            `;
        });
}

// 绑定查看员工详情按钮事件
function bindViewEmployeeButtons() {
    const viewButtons = document.querySelectorAll('.view-employee');
    viewButtons.forEach(button => {
        button.addEventListener('click', function() {
            const employeeId = this.getAttribute('data-id');
            showEmployeeDetail(employeeId);
        });
    });
}

// 初始化员工相关模态框
function initEmployeeModals() {
    // 员工详情模态框
    const detailModal = document.getElementById('employee-detail-modal');
    if (detailModal) {
        const closeBtn = detailModal.querySelector('.close-modal');
        
        closeBtn.addEventListener('click', function() {
            detailModal.style.display = 'none';
        });
        
        window.addEventListener('click', function(event) {
            if (event.target === detailModal) {
                detailModal.style.display = 'none';
            }
        });
        
        // 绑定修改信息按钮
        const updateBtn = document.getElementById('update-employee-btn');
        if (updateBtn) {
            updateBtn.addEventListener('click', function() {
                showUpdateEmployeeForm();
            });
        }
        
        // 绑定开除员工按钮
        const fireBtn = document.getElementById('fire-employee-btn');
        if (fireBtn) {
            fireBtn.addEventListener('click', function() {
                confirmFireEmployee();
            });
        }
    }
    
    // 修改员工信息模态框
    const updateModal = document.getElementById('update-employee-modal');
    if (updateModal) {
        const closeBtn = updateModal.querySelector('.close-modal');
        const cancelBtn = document.getElementById('cancel-update');
        
        closeBtn.addEventListener('click', function() {
            updateModal.style.display = 'none';
        });
        
        if (cancelBtn) {
            cancelBtn.addEventListener('click', function() {
                updateModal.style.display = 'none';
            });
        }
        
        window.addEventListener('click', function(event) {
            if (event.target === updateModal) {
                updateModal.style.display = 'none';
            }
        });
        
        // 绑定表单提交事件
        const form = document.getElementById('update-employee-form');
        if (form) {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                updateEmployeeInfo();
            });
        }
    }
}

// 显示员工详情
function showEmployeeDetail(employeeId) {
    const modal = document.getElementById('employee-detail-modal');
    const detailContent = document.getElementById('employee-detail-content');
    const actionsDiv = document.getElementById('employee-actions');
    
    if (!modal || !detailContent || !actionsDiv) return;
    
    detailContent.innerHTML = '<div class="loading">加载中...</div>';
    modal.style.display = 'block';
    
    // 存储当前查看的员工ID，用于后续操作
    modal.setAttribute('data-employee-id', employeeId);
    
    // console.log('获取员工详情，用户ID:', employeeId);
    fetch(`getEmployeeDetail?id=${employeeId}`)
        .then(response => {
            // console.log('员工详情API响应状态:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP错误，状态码: ${response.status}`);
            }
            return response.json();
        })

        .then(data => {
            // console.log('员工详情API响应数据:', data);
            if (data.success) {
                const employee = data.employee;
                let html = `
                    <div class="employee-detail">
                        <p><strong>员工ID：</strong>${employee.id || employee.userId || ''}</p>
                        <p><strong>姓名：</strong>${employee.userName || ''}</p>
                        <p><strong>电话：</strong>${employee.userPhone || ''}</p>
                        <p><strong>年龄：</strong>${employee.userAge || ''}</p>
                        <p><strong>身份证：</strong>${data.maskedIdCard || '未设置'}</p>
                        <p><strong>职位：</strong>${employee.position || '未设置'}</p>
                        <p><strong>薪资：</strong>${employee.baseSalary ? employee.baseSalary + ' 元' : '未设置'}</p>
                        <p><strong>邮箱：</strong>${employee.userEmail || '未设置'}</p>
                        <p><strong>住址：</strong>${employee.userAddress || '未设置'}</p>
                        <p><strong>员工编号：</strong>${employee.employeeNumber || '未设置'}</p>
                    </div>
                `;
                detailContent.innerHTML = html;
                
                // 存储当前职位和薪资，用于修改表单
                if (employee.position) {
                    modal.setAttribute('data-position', employee.position);
                }
                if (employee.baseSalary) {
                    modal.setAttribute('data-salary', employee.baseSalary);
                }
                
                // 根据员工是否是负责人或自己，决定是否显示操作按钮
                const updateBtn = document.getElementById('update-employee-btn');
                const fireBtn = document.getElementById('fire-employee-btn');
                
                if (data.isEmployeeManager || data.isManagerSelf) {
                    // 如果员工是负责人或是负责人自己，隐藏操作按钮
                    actionsDiv.style.display = 'none';
                    
                    // 添加提示信息
                    let tipMessage = '';
                    if (data.isEmployeeManager) {
                        tipMessage = '注意：负责人信息不可修改';
                    }
                    if (data.isManagerSelf) {
                        tipMessage = '注意：不能修改或开除自己';
                    }
                    
                    if (tipMessage) {
                        const tipElement = document.createElement('div');
                        tipElement.className = 'alert alert-warning';
                        tipElement.textContent = tipMessage;
                        detailContent.appendChild(tipElement);
                    }
                } else {
                    // 显示操作按钮
                    actionsDiv.style.display = 'block';
                }
            } else {
                detailContent.innerHTML = `<div class="alert alert-danger">${data.message || '获取员工详情失败'}</div>`;
            }
        })
        .catch(error => {
            // console.error('获取员工详情出错:', error);
            detailContent.innerHTML = `
                <div class="alert alert-danger">
                    <p>加载员工详情失败，请检查网络连接或联系管理员</p>
                    <p>错误详情: ${error.message}</p>
                </div>
            `;
            actionsDiv.style.display = 'none';
        });
}

// 显示修改员工信息表单
function showUpdateEmployeeForm() {
    const detailModal = document.getElementById('employee-detail-modal');
    const updateModal = document.getElementById('update-employee-modal');
    const employeeId = detailModal.getAttribute('data-employee-id');
    const position = detailModal.getAttribute('data-position') || '';
    const salary = detailModal.getAttribute('data-salary') || '';
    
    if (!updateModal || !employeeId) return;
    
    // 填充表单数据
    document.getElementById('update-employee-id').value = employeeId;
    document.getElementById('update-position').value = position;
    document.getElementById('update-salary').value = salary;
    
    // 显示修改表单模态框
    updateModal.style.display = 'block';
}

// 更新员工信息
function updateEmployeeInfo() {
    const updateModal = document.getElementById('update-employee-modal');
    const employeeId = document.getElementById('update-employee-id').value;
    const position = document.getElementById('update-position').value;
    const salary = document.getElementById('update-salary').value;
    
    // 构建表单数据
    const formData = new URLSearchParams();
    formData.append('id', employeeId);
    formData.append('position', encodeURIComponent(position));
    formData.append('salary', salary);
    
    // 禁用提交按钮
    const submitBtn = document.querySelector('#update-employee-form button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.textContent = '保存中...';
    
    fetch('updateEmployee', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 关闭修改表单模态框
            updateModal.style.display = 'none';
            
            // 刷新员工详情和列表
            const employeeId = document.getElementById('update-employee-id').value;
            showEmployeeDetail(employeeId);
            loadEmployees();
            
            // 显示成功提示
            alert(data.message || '员工信息更新成功');
        } else {
            alert(data.message || '员工信息更新失败');
        }
        
        // 恢复提交按钮
        submitBtn.disabled = false;
        submitBtn.textContent = '保存';
    })
    .catch(error => {
        // console.error('更新员工信息出错:', error);
        alert('系统错误，请稍后再试');
        
        // 恢复提交按钮
        submitBtn.disabled = false;
        submitBtn.textContent = '保存';
    });
}

// 确认开除员工
function confirmFireEmployee() {
    const detailModal = document.getElementById('employee-detail-modal');
    const employeeId = detailModal.getAttribute('data-employee-id');
    
    if (!employeeId) return;
    
    if (confirm('确定要开除该员工吗？此操作不可撤销！')) {
        fireEmployee(employeeId);
    }
}

// 开除员工
function fireEmployee(employeeId) {
    const formData = new URLSearchParams();
    formData.append('id', employeeId);
    
    fetch('fireEmployee', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 关闭员工详情模态框
            const detailModal = document.getElementById('employee-detail-modal');
            detailModal.style.display = 'none';
            
            // 刷新员工列表
            loadEmployees();
            
            // 显示成功提示
            alert(data.message || '员工已成功开除');
        } else {
            alert(data.message || '开除员工失败');
        }
    })
    .catch(error => {
        // console.error('开除员工出错:', error);
        alert('系统错误，请稍后再试');
    });
} 

// 在文件末尾添加打卡设置和打卡记录相关功能

// 初始化打卡设置功能
function initClockSettings() {
    // 更新打卡设置页面内容
    const clockSettingsContainer = document.getElementById('clock-settings-content');
    if (!clockSettingsContainer) return;
    
    // 获取公司ID
    const companyId = getCurrentCompanyId();
    if (!companyId) {
        // 显示加载中，并尝试重新获取用户信息
        clockSettingsContainer.innerHTML = '<div class="loading">正在加载公司信息...</div>';
        
        // 重新获取用户信息
        fetchCurrentUserInfo();
        
        // 延迟1秒后再次尝试初始化
        setTimeout(() => {
            const newCompanyId = getCurrentCompanyId();
            if (newCompanyId) {
                loadClockSettings(newCompanyId);
            } else {
                clockSettingsContainer.innerHTML = '<div class="error-message">未能获取公司信息，请刷新页面重试</div>';
            }
        }, 1000);
        return;
    }
    
    // 加载打卡设置
    loadClockSettings(companyId);
}

// 加载打卡设置
function loadClockSettings(companyId) {
    const clockSettingsContainer = document.getElementById('clock-settings-content');
    clockSettingsContainer.innerHTML = '<div class="loading">加载中...</div>';
    
    fetch(`api/attendance/setting?companyId=${companyId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayClockSettings(data.data, companyId);
            } else {
                // 如果没有设置，显示新建表单
                displayNewClockSettingsForm(companyId);
            }
        })
        .catch(error => {
            // console.error('获取打卡设置失败:', error);
            clockSettingsContainer.innerHTML = '<div class="error-message">获取打卡设置失败，请稍后重试</div>';
        });
}

// 显示打卡设置
function displayClockSettings(setting, companyId) {
    const clockSettingsContainer = document.getElementById('clock-settings-content');
    
    // 格式化时间
    // 检查时间格式并进行处理
    function formatTimeString(timeStr) {
        if (!timeStr) return "未设置";
        
        // 如果时间字符串已经是HH:MM:SS格式，直接提取HH:MM部分
        if (typeof timeStr === 'string') {
            // 处理格式为 "HH:MM:SS" 的字符串
            if (timeStr.match(/^\d{1,2}:\d{1,2}(:\d{1,2})?$/)) {
                return timeStr.substring(0, 5);
            }
            
            // 处理格式为 "1970-01-01THH:MM:SS.000Z" 的ISO字符串
            if (timeStr.includes('T') && timeStr.includes('Z')) {
                const date = new Date(timeStr);
                if (!isNaN(date.getTime())) {
                    return date.toTimeString().substring(0, 5);
                }
            }
        }
        
        // 尝试直接使用 toString() 方法
        if (timeStr.toString) {
            const timeString = timeStr.toString();
            // 如果转换后的字符串包含冒号，可能是时间格式
            if (timeString.includes(':')) {
                // 提取 HH:MM 部分
                const match = timeString.match(/(\d{1,2}:\d{1,2})/);
                if (match) {
                    return match[0];
                }
            }
        }
        
        // 尝试创建日期对象
        try {
            // 对于数字类型，可能是毫秒时间戳
            if (typeof timeStr === 'number') {
                const date = new Date(timeStr);
                if (!isNaN(date.getTime())) {
                    // 格式化为 HH:MM
                    const hours = date.getHours().toString().padStart(2, '0');
                    const minutes = date.getMinutes().toString().padStart(2, '0');
                    return `${hours}:${minutes}`;
                }
            }
            
            // 尝试解析其他格式
            const date = new Date(`1970-01-01T${timeStr}`);
            if (!isNaN(date.getTime())) {
                const hours = date.getHours().toString().padStart(2, '0');
                const minutes = date.getMinutes().toString().padStart(2, '0');
                return `${hours}:${minutes}`;
            }
        } catch (e) {
            // console.error('Error formatting time:', e);
        }
        
        // 如果所有方法都失败，返回原始值
        return typeof timeStr === 'string' ? timeStr : "未知时间格式";
    }
    
    const checkInStartTime = formatTimeString(setting.checkInStartTime);
    const checkInEndTime = formatTimeString(setting.checkInEndTime);
    const checkOutStartTime = formatTimeString(setting.checkOutStartTime);
    const checkOutEndTime = formatTimeString(setting.checkOutEndTime);
    
    let html = `
        <div class="settings-box">
            <div class="settings-header">
                <h3>当前打卡设置</h3>
                <button id="edit-settings-btn" class="btn btn-primary"><i class="fas fa-edit"></i> 修改设置</button>
            </div>
            <div class="settings-content">
                <div class="settings-group">
                    <label>上班打卡时间范围：</label>
                    <span>${checkInStartTime} - ${checkInEndTime}</span>
                </div>
                <div class="settings-group">
                    <label>下班打卡时间范围：</label>
                    <span>${checkOutStartTime} - ${checkOutEndTime}</span>
                </div>
            </div>
        </div>
        
        <div id="edit-settings-form-container" style="display: none;">
            <form id="clock-settings-form" class="standard-form">
                <input type="hidden" id="company-id" value="${companyId}">
                
                <div class="form-group">
                    <label for="check-in-start-time">上班打卡开始时间：</label>
                    <input type="time" id="check-in-start-time" class="form-control" value="${checkInStartTime}" required>
                </div>
                
                <div class="form-group">
                    <label for="check-in-end-time">上班打卡结束时间：</label>
                    <input type="time" id="check-in-end-time" class="form-control" value="${checkInEndTime}" required>
                </div>
                
                <div class="form-group">
                    <label for="check-out-start-time">下班打卡开始时间：</label>
                    <input type="time" id="check-out-start-time" class="form-control" value="${checkOutStartTime}" required>
                </div>
                
                <div class="form-group">
                    <label for="check-out-end-time">下班打卡结束时间：</label>
                    <input type="time" id="check-out-end-time" class="form-control" value="${checkOutEndTime}" required>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">保存设置</button>
                    <button type="button" id="cancel-edit-btn" class="btn btn-secondary">取消</button>
                </div>
            </form>
        </div>
    `;
    
    clockSettingsContainer.innerHTML = html;
    
    // 添加修改按钮点击事件
    document.getElementById('edit-settings-btn').addEventListener('click', function() {
        document.getElementById('edit-settings-form-container').style.display = 'block';
    });
    
    // 添加取消按钮点击事件
    document.getElementById('cancel-edit-btn').addEventListener('click', function() {
        document.getElementById('edit-settings-form-container').style.display = 'none';
    });
    
    // 添加表单提交事件
    document.getElementById('clock-settings-form').addEventListener('submit', function(event) {
        event.preventDefault();
        saveClockSettings();
    });
}

// 显示新建打卡设置表单
function displayNewClockSettingsForm(companyId) {
    const clockSettingsContainer = document.getElementById('clock-settings-content');
    
    let html = `
        <div class="settings-box">
            <div class="settings-header">
                <h3>创建打卡设置</h3>
            </div>
            <div class="settings-content">
                <p>您尚未设置打卡时间，请创建打卡设置</p>
                
                <form id="clock-settings-form" class="standard-form">
                    <input type="hidden" id="company-id" value="${companyId}">
                    
                    <div class="form-group">
                        <label for="check-in-start-time">上班打卡开始时间：</label>
                        <input type="time" id="check-in-start-time" class="form-control" value="08:30" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="check-in-end-time">上班打卡结束时间：</label>
                        <input type="time" id="check-in-end-time" class="form-control" value="09:30" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="check-out-start-time">下班打卡开始时间：</label>
                        <input type="time" id="check-out-start-time" class="form-control" value="17:30" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="check-out-end-time">下班打卡结束时间：</label>
                        <input type="time" id="check-out-end-time" class="form-control" value="18:30" required>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">保存设置</button>
                    </div>
                </form>
            </div>
        </div>
    `;
    
    clockSettingsContainer.innerHTML = html;
    
    // 添加表单提交事件
    document.getElementById('clock-settings-form').addEventListener('submit', function(event) {
        event.preventDefault();
        saveClockSettings();
    });
}

// 保存打卡设置
function saveClockSettings() {
    const companyId = document.getElementById('company-id').value;
    const checkInStartTime = document.getElementById('check-in-start-time').value;
    const checkInEndTime = document.getElementById('check-in-end-time').value;
    const checkOutStartTime = document.getElementById('check-out-start-time').value;
    const checkOutEndTime = document.getElementById('check-out-end-time').value;
    
    // 验证时间
    if (!checkInStartTime || !checkInEndTime || !checkOutStartTime || !checkOutEndTime) {
        alert('所有时间都必须填写');
        return;
    }
    
    // 发送请求
    fetch('api/attendance/setting', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            companyId: companyId,
            checkInStartTime: checkInStartTime,
            checkInEndTime: checkInEndTime,
            checkOutStartTime: checkOutStartTime,
            checkOutEndTime: checkOutEndTime
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('打卡设置保存成功');
                loadClockSettings(companyId); // 重新加载设置
            } else {
                alert('打卡设置保存失败：' + data.message);
            }
        })
        .catch(error => {
            // console.error('保存打卡设置失败:', error);
            alert('保存打卡设置失败，请稍后重试');
        });
}

// 初始化查看打卡记录功能
function initClockRecords() {
    // 更新打卡记录页面内容
    const clockRecordsContainer = document.getElementById('clock-records-content');
    if (!clockRecordsContainer) return;
    
    // 获取公司ID
    const companyId = getCurrentCompanyId();
    if (!companyId) {
        // 显示加载中，并尝试重新获取用户信息
        clockRecordsContainer.innerHTML = '<div class="loading">正在加载公司信息...</div>';
        
        // 重新获取用户信息
        fetchCurrentUserInfo();
        
        // 延迟1秒后再次尝试初始化
        setTimeout(() => {
            const newCompanyId = getCurrentCompanyId();
            if (newCompanyId) {
                // 构建页面内容
                buildClockRecordsUI(clockRecordsContainer);
                
                // 获取当前日期
                const today = new Date();
                const year = today.getFullYear();
                const month = String(today.getMonth() + 1).padStart(2, '0');
                const day = String(today.getDate()).padStart(2, '0');
                const formattedDate = `${year}-${month}-${day}`;
                
                // 加载今日打卡记录
                loadCompanyAttendanceRecords(newCompanyId, formattedDate);
            } else {
                clockRecordsContainer.innerHTML = '<div class="error-message">未能获取公司信息，请刷新页面重试</div>';
            }
        }, 1000);
        return;
    }
    
    // 构建页面内容
    buildClockRecordsUI(clockRecordsContainer);
    
    // 获取当前日期
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    const formattedDate = `${year}-${month}-${day}`;
    
    // 加载今日打卡记录
    loadCompanyAttendanceRecords(companyId, formattedDate);
}

// 构建打卡记录UI
function buildClockRecordsUI(container) {
    // 获取当前日期并格式化为YYYY-MM-DD
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    const formattedDate = `${year}-${month}-${day}`;
    
    let html = `
        <div class="filter-container">
            <div class="date-filter">
                <label for="record-date">日期：</label>
                <input type="date" id="record-date" class="form-control" value="${formattedDate}">
            </div>
            <button class="refresh-btn" id="refresh-records-btn"><i class="fas fa-sync-alt"></i> 刷新记录</button>
        </div>
        
        <div id="today-count-container" class="count-container">
            <div class="loading">加载中...</div>
        </div>
        
        <div id="attendance-records-container">
            <div class="loading">加载中...</div>
        </div>
    `;
    
    container.innerHTML = html;
    
    // 添加日期选择器变化事件，自动筛选
    document.getElementById('record-date').addEventListener('change', function() {
        const date = this.value;
        // console.log("日期选择器已更改，选择日期:", date);
        if (date) {
            loadCompanyAttendanceRecords(getCurrentCompanyId(), date);
        }
    });
    
    // 添加刷新记录按钮点击事件
    document.getElementById('refresh-records-btn').addEventListener('click', function() {
        const date = document.getElementById('record-date').value;
        // console.log("刷新按钮点击，使用日期:", date);
        if (date) {
            loadCompanyAttendanceRecords(getCurrentCompanyId(), date);
        } else {
            // 如果没有日期，使用当天日期
            const today = new Date();
            const formattedDate = today.toISOString().split('T')[0];
            loadCompanyAttendanceRecords(getCurrentCompanyId(), formattedDate);
        }
    });
}

// 加载公司打卡记录
function loadCompanyAttendanceRecords(companyId, date = null) {
    const recordsContainer = document.getElementById('attendance-records-container');
    const countContainer = document.getElementById('today-count-container');
    
    if (!recordsContainer || !countContainer) {
        // console.error('找不到打卡记录容器或统计容器');
        return;
    }
    
    recordsContainer.innerHTML = '<div class="loading">加载中...</div>';
    countContainer.innerHTML = '<div class="loading">加载中...</div>';
    
    // 如果没有提供日期，使用当天日期
    if (!date) {
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        date = `${year}-${month}-${day}`;
        // console.log('未提供日期，使用当前日期:', date);
    }
    
    let url = `api/attendance/records?type=company&companyId=${companyId}&date=${date}`;
    
    // console.log('请求打卡记录URL:', url);
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            // console.log('获取到打卡记录数据:', data);
            // console.log('打卡统计数据:', data.todayCount);
            // console.log('打卡记录数据:', data.data);
            
            if (data.success) {
                displayCompanyAttendanceRecords(data.data);
                displayTodayCount(data.todayCount, date);
            } else {
                recordsContainer.innerHTML = `<div class="error-message">${data.message}</div>`;
                countContainer.innerHTML = '';
            }
        })
        .catch(error => {
            // console.error('获取打卡记录失败:', error);
            recordsContainer.innerHTML = '<div class="error-message">获取打卡记录失败，请稍后重试</div>';
            countContainer.innerHTML = '';
        });
}

// 显示今日打卡人数
function displayTodayCount(count, date = null) {
    const container = document.getElementById('today-count-container');
    
    if (!container) return;
    
    const today = date ? new Date(date) : new Date();
    const formattedDate = formatDateForDisplay(today.toISOString().split('T')[0]);
    
    let html = `
        <h3>打卡统计</h3>
        <div class="count-info">
            <div class="count-number">${count.checkedInCount || 0} / ${count.totalEmployees || 0 }</div>
            <div class="count-date">${formattedDate}</div>
        </div>
        <div class="count-details">
            <div class="count-item">
                <span class="count-label">已打卡:</span>
                <span class="count-value">${count.checkedInCount || 0}人</span>
            </div>
            <div class="count-item">
                <span class="count-label">已签退:</span>
                <span class="count-value">${count.checkedOutCount || 0}人</span>
            </div>
        </div>
    `;
    
    container.innerHTML = html;
}

// 显示公司打卡记录
function displayCompanyAttendanceRecords(records) {
    const container = document.getElementById('attendance-records-container');
    
    // console.log('显示打卡记录，记录数量:', records ? records.length : 0);
    
    if (!records || records.length === 0) {
        // 尝试从服务器获取的数据中提取用户ID
        const todayCount = document.querySelector('.count-number');
        const countText = todayCount ? todayCount.textContent : '';
        
        // console.log('打卡统计显示:', countText);
        
        // 如果打卡统计显示有人打卡，但记录为空，显示特殊消息
        if (countText && countText.trim() !== '0 / 1' && countText.trim() !== '0 / 0') {
            container.innerHTML = '<div class="no-records">有打卡记录，但无法显示详细信息。请联系系统管理员。</div>';
        } else {
            container.innerHTML = '<div class="no-records">暂无打卡记录</div>';
        }
        return;
    }
    
    // 按日期分组记录
    const recordsByDate = {};
    records.forEach(record => {
        // console.log('处理记录:', record);
        
        // 提取日期部分
        let datePart = '';
        if (record.recordDate) {
            datePart = record.recordDate.split(' ')[0];
        } else if (record.attendanceDate) {
            datePart = record.attendanceDate.split(' ')[0];
        } else {
            // 如果没有日期字段，使用当前日期
            const today = new Date();
            datePart = today.toISOString().split('T')[0];
        }
        
        // console.log('记录日期:', datePart);
        
        if (!recordsByDate[datePart]) {
            recordsByDate[datePart] = [];
        }
        recordsByDate[datePart].push(record);
    });
    
    // console.log('按日期分组后的记录:', recordsByDate);
    
    let html = '';
    
    // 创建分页控件
    const totalPages = Object.keys(recordsByDate).length;
    const itemsPerPage = 1; // 每页显示一天的记录
    let currentPage = 1;
    
    // 创建表格
    html += `
        <table class="records-table">
            <thead>
                <tr>
                    <th>员工ID</th>
                    <th>员工姓名</th>
                    <th>上班时间</th>
                    <th>下班时间</th>
                    <th>状态</th>
                </tr>
            </thead>
            <tbody id="records-tbody">
            </tbody>
        </table>
        
        <div class="pagination" id="records-pagination">
        </div>
    `;
    
    container.innerHTML = html;
    
    // 更新分页控件
    function updatePagination() {
        const pagination = document.getElementById('records-pagination');
        let paginationHtml = '';
        
        // 上一页按钮
        paginationHtml += `<button ${currentPage === 1 ? 'disabled' : ''} id="prev-page">&laquo; 上一页</button>`;
        
        // 页码按钮
        const dates = Object.keys(recordsByDate).sort().reverse(); // 按日期倒序排列
        for (let i = 0; i < dates.length; i++) {
            const pageNum = i + 1;
            paginationHtml += `<button class="${pageNum === currentPage ? 'active' : ''}" data-page="${pageNum}" data-date="${dates[i]}">${formatDateForDisplay(dates[i])}</button>`;
        }
        
        // 下一页按钮
        paginationHtml += `<button ${currentPage === totalPages ? 'disabled' : ''} id="next-page">下一页 &raquo;</button>`;
        
        pagination.innerHTML = paginationHtml;
        
        // 添加页码按钮事件
        document.querySelectorAll('#records-pagination button[data-page]').forEach(btn => {
            btn.addEventListener('click', function() {
                currentPage = parseInt(this.getAttribute('data-page'));
                const date = this.getAttribute('data-date');
                updateRecordsTable(date);
                updatePagination();
            });
        });
        
        // 添加上一页按钮事件
        const prevBtn = document.getElementById('prev-page');
        if (prevBtn) {
            prevBtn.addEventListener('click', function() {
                if (currentPage > 1) {
                    currentPage--;
                    const date = Object.keys(recordsByDate).sort().reverse()[currentPage - 1];
                    updateRecordsTable(date);
                    updatePagination();
                }
            });
        }
        
        // 添加下一页按钮事件
        const nextBtn = document.getElementById('next-page');
        if (nextBtn) {
            nextBtn.addEventListener('click', function() {
                if (currentPage < totalPages) {
                    currentPage++;
                    const date = Object.keys(recordsByDate).sort().reverse()[currentPage - 1];
                    updateRecordsTable(date);
                    updatePagination();
                }
            });
        }
    }
    
    // 更新表格内容
    function updateRecordsTable(date) {
        const tbody = document.getElementById('records-tbody');
        const recordsForDate = recordsByDate[date];
        
        // console.log('更新表格，日期:', date, '记录:', recordsForDate);
        
        let tableHtml = '';
        
        // 不再添加日期标题行，直接添加记录行
        recordsForDate.forEach(record => {
            // console.log('处理表格行记录:', record);
            
            // 确定打卡状态
            let statusClass = 'status-complete';
            let statusText = '正常';
            
            if (!record.checkOutTime) {
                statusClass = 'status-incomplete';
                statusText = '未下班';
            } else {
                // 保持正常状态
                statusClass = 'status-complete';
                statusText = '正常';
            }
            
            // 获取员工ID和姓名
            const employeeId = record.employeeId || record.employeeNumber || record.userId || '未知';
            const employeeName = record.employeeName || record.userName || '未知';
            
            tableHtml += `
                <tr>
                    <td>${employeeId}</td>
                    <td>${employeeName}</td>
                    <td>
                        ${record.checkInTime ? formatTimeOnly(record.checkInTime) : '未打卡'}
                    </td>
                    <td>
                        ${record.checkOutTime ? formatTimeOnly(record.checkOutTime) : '未打卡'}
                    </td>
                    <td class="${statusClass}">${statusText}</td>
                </tr>
            `;
        });
        
        tbody.innerHTML = tableHtml;
    }
    
    // 初始化显示第一页
    if (Object.keys(recordsByDate).length > 0) {
        const initialDate = Object.keys(recordsByDate).sort().reverse()[0];
        updateRecordsTable(initialDate);
        updatePagination();
    } else {
        document.getElementById('records-tbody').innerHTML = '<tr><td colspan="5" class="no-records">暂无打卡记录</td></tr>';
    }
}

// 格式化日期显示
function formatDateForDisplay(dateStr) {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    const weekday = weekdays[date.getDay()];
    
    return `${year}/${month}/${day} (星期${weekday})`;
}

// 只显示时间部分
function formatTimeOnly(dateTimeStr) {
    if (!dateTimeStr) return '';
    const parts = dateTimeStr.split(' ');
    if (parts.length > 1) {
        return parts[1];
    }
    return dateTimeStr;
}

// 获取当前公司ID
function getCurrentCompanyId() {
    // 首先检查全局变量
    if (currentCompanyId) {
        return currentCompanyId;
    }
    
    // 如果全局变量中没有，检查页面中的隐藏字段
    const companyIdElement = document.getElementById('company-id');
    if (companyIdElement && companyIdElement.value) {
        return companyIdElement.value;
    }
    
    // 如果页面中没有，检查当前用户对象
    if (window.currentUser && window.currentUser.companyId) {
        return window.currentUser.companyId;
    }
    
    // 如果都没有找到，返回null
    return null;
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 获取所有菜单项
    const menuItems = document.querySelectorAll('.submenu-item a');
    
    // 添加点击事件
    menuItems.forEach(item => {
        item.addEventListener('click', function() {
            const target = this.getAttribute('data-target');
            
            // 如果点击的是打卡设置
            if (target === 'clock-settings') {
                initClockSettings();
            }
            
            // 如果点击的是查看打卡记录
            if (target === 'clock-records') {
                initClockRecords();
            }
            
            // 如果点击的是任务派遣与审核
            if (target === 'task-management') {
                initTaskManagement();
            }
            
            // 如果点击的是个人与公司资料
            if (target === 'profile') {
                initProfileManagement();
            }
        });
    });
    
    // 初始化任务派遣与审核功能（页面加载时也初始化）
    initTaskManagement();
});

// 获取当前用户信息
function fetchCurrentUserInfo() {
    fetch('getCurrentUser')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.user) {
                // 保存用户信息到全局变量
                window.currentUser = data.user;
                
                // 如果是公司负责人，保存公司ID
                if (data.user.role === 1 && data.user.companyId) {
                    currentCompanyId = data.user.companyId;
                    // console.log('获取到公司ID:', currentCompanyId);
                    
                    // 更新页面中的隐藏字段
                    const companyIdFields = document.querySelectorAll('.company-id-field');
                    companyIdFields.forEach(field => {
                        field.value = currentCompanyId;
                    });
                }
            }
        })
        .catch(error => {
            // console.error('获取用户信息失败:', error);
        });
}

// 显示消息提示
function showMessage(message, type = 'info') {
    // 创建消息元素
    const messageElement = document.createElement('div');
    messageElement.className = `message-toast ${type}`;
    messageElement.textContent = message;
    
    // 添加到页面
    document.body.appendChild(messageElement);
    
    // 显示动画
    setTimeout(() => {
        messageElement.classList.add('show');
    }, 10);
    
    // 3秒后移除
    setTimeout(() => {
        messageElement.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(messageElement);
        }, 300);
    }, 3000);
}

// 任务派遣与审核功能
function initTaskManagement() {
    // console.log('初始化任务派遣与审核功能...');
    const taskContent = document.getElementById('task-content');
    if (!taskContent) {
        // console.error('无法找到任务内容容器元素');
        return;
    }
    
    // 创建任务派遣表单和任务列表容器
    taskContent.innerHTML = `
        <div class="task-management-container">
            <div class="task-dispatch-form">
                <h3>派遣新任务</h3>
                <form id="task-dispatch-form">
                    <div class="form-group">
                        <label for="task-employee">选择员工</label>
                        <select id="task-employee" class="form-control" required>
                            <option value="">-- 请选择员工 --</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="task-title">任务标题</label>
                        <input type="text" id="task-title" class="form-control" required placeholder="请输入任务标题">
                    </div>
                    <div class="form-group">
                        <label for="task-content">任务内容</label>
                        <textarea id="task-content-input" class="form-control" rows="4" required placeholder="请输入任务详细内容"></textarea>
                    </div>
                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">派遣任务</button>
                    </div>
                </form>
            </div>
            
            <div class="task-list-container">
                <h3>任务列表</h3>
                <div class="filter-container">
                    <button class="filter-btn active" data-status="-1">全部</button>
                    <button class="filter-btn" data-status="0">派遣中</button>
                    <button class="filter-btn" data-status="1">完成待确认</button>
                    <button class="filter-btn" data-status="2">已完成</button>
                    <button class="refresh-btn" id="refresh-tasks-btn"><i class="fas fa-sync-alt"></i> 刷新</button>
                </div>
                <div id="task-list">
                    <div class="loading">加载中...</div>
                </div>
            </div>
        </div>
        
        <!-- 任务确认模态框 -->
        <div id="task-confirm-modal" class="modal">
            <div class="modal-content">
                <span class="close-modal">&times;</span>
                <h3>确认任务完成</h3>
                <div id="task-confirm-content"></div>
                <div class="form-group">
                    <label for="task-score">评分 (0-10分)</label>
                    <input type="range" id="task-score" min="0" max="10" value="7" class="form-control">
                    <div class="score-display">当前评分: <span id="score-value">7</span></div>
                </div>
                <div class="modal-actions">
                    <button id="confirm-complete-btn" class="btn btn-primary">确认完成</button>
                    <button id="mark-incomplete-btn" class="btn btn-danger">未能完成</button>
                </div>
            </div>
        </div>
        
        <!-- 修改评分模态框 -->
        <div id="edit-score-modal" class="modal">
            <div class="modal-content">
                <span class="close-modal">&times;</span>
                <h3>修改任务评分</h3>
                <div id="edit-score-content"></div>
                <div class="form-group">
                    <label for="edit-task-score">评分 (0-10分)</label>
                    <input type="range" id="edit-task-score" min="0" max="10" value="7" class="form-control">
                    <div class="score-display">当前评分: <span id="edit-score-value">7</span></div>
                </div>
                <div class="modal-actions">
                    <button id="update-score-btn" class="btn btn-primary">保存修改</button>
                    <button id="cancel-edit-score-btn" class="btn btn-secondary">取消</button>
                </div>
            </div>
        </div>
    `;
    
    // 加载员工列表
    loadEmployeeOptions();
    
    // 加载任务列表
    loadTasks();
    
    // 添加任务派遣表单提交事件
    document.getElementById('task-dispatch-form').addEventListener('submit', function(e) {
        e.preventDefault();
        dispatchTask();
    });
    
    // 添加任务列表筛选事件
    document.querySelectorAll('.task-list-container .filter-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.task-list-container .filter-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            loadTasks(this.dataset.status, 1); // 切换筛选时重置为第一页
        });
    });
    
    // 添加刷新按钮事件
    document.getElementById('refresh-tasks-btn').addEventListener('click', function() {
        const activeFilter = document.querySelector('.task-list-container .filter-btn.active');
        loadTasks(activeFilter ? activeFilter.dataset.status : -1, 1); // 刷新时重置为第一页
    });
    
    // 添加评分滑块事件
    const scoreSlider = document.getElementById('task-score');
    const scoreValue = document.getElementById('score-value');
    scoreSlider.addEventListener('input', function() {
        scoreValue.textContent = this.value;
    });
    
    // 添加修改评分滑块事件
    const editScoreSlider = document.getElementById('edit-task-score');
    const editScoreValue = document.getElementById('edit-score-value');
    editScoreSlider.addEventListener('input', function() {
        editScoreValue.textContent = this.value;
    });
    
    // 添加确认任务模态框关闭事件
    document.querySelector('#task-confirm-modal .close-modal').addEventListener('click', function() {
        document.getElementById('task-confirm-modal').style.display = 'none';
    });
    
    // 添加修改评分模态框关闭事件
    document.querySelector('#edit-score-modal .close-modal').addEventListener('click', function() {
        document.getElementById('edit-score-modal').style.display = 'none';
    });
    
    // 添加取消修改评分按钮事件
    document.getElementById('cancel-edit-score-btn').addEventListener('click', function() {
        document.getElementById('edit-score-modal').style.display = 'none';
    });
}

// 加载员工选项
function loadEmployeeOptions() {
    // console.log('开始加载员工选项...');
    
    // 首先获取当前用户信息
    fetch('./api/user/current')
        .then(response => response.json())
        .then(userData => {
            if (!userData.success || !userData.user) {
                // console.error('获取当前用户信息失败');
                throw new Error('获取当前用户信息失败');
            }
            
            const currentUserId = userData.user.id;
            // console.log('当前用户ID:', currentUserId);
            
            // 然后获取员工列表
            return fetch('./api/employees')
                .then(response => {
                    // console.log('员工API响应状态:', response.status);
                    if (!response.ok) {
                        // console.error('员工API请求失败，状态码:', response.status);
                        throw new Error(`HTTP错误，状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    // console.log('员工API响应数据:', data);
                    if (data.success) {
                        const employeeSelect = document.getElementById('task-employee');
                        if (!employeeSelect) {
                            // console.error('无法找到员工选择框元素');
                            return;
                        }
                        employeeSelect.innerHTML = '<option value="">-- 请选择员工 --</option>';
                        
                        if (data.employees && Array.isArray(data.employees)) {
                            // 过滤掉当前用户（公司负责人）
                            const filteredEmployees = data.employees.filter(employee => employee.userId !== currentUserId);
                            
                            filteredEmployees.forEach(employee => {
                                const option = document.createElement('option');
                                option.value = employee.userId;
                                option.textContent = `${employee.userName} (${employee.position})`;
                                employeeSelect.appendChild(option);
                            });
                            // console.log('成功加载了', filteredEmployees.length, '名员工（排除公司负责人）');
                            
                            if (filteredEmployees.length === 0) {
                                showMessage('您的公司当前没有可派遣任务的员工，请先招聘员工', 'info');
                            }
                        } else {
                            // console.warn('员工数据不是数组或为空:', data.employees);
                            showMessage('员工数据格式不正确', 'error');
                        }
                    } else {
                        // console.error('加载员工列表失败:', data.message);
                        showMessage('加载员工列表失败: ' + data.message, 'error');
                    }
                });
        })
        .catch(error => {
            // console.error('加载员工列表出错:', error);
            showMessage('加载员工列表出错: ' + error.message, 'error');
        });
}

// 加载任务列表
function loadTasks(status = -1, page = 1) {
    // console.log('开始加载任务列表，状态过滤:', status, '页码:', page);
    const taskList = document.getElementById('task-list');
    if (!taskList) {
        // console.error('无法找到任务列表元素');
        return;
    }
    
    taskList.innerHTML = '<div class="loading">加载中...</div>';
    
    const apiUrl = `./api/tasks?type=manager${status !== -1 ? '&status=' + status : ''}`;
    // console.log('任务API请求URL:', apiUrl);
    
    fetch(apiUrl)
        .then(response => {
            // console.log('任务API响应状态:', response.status);
            if (!response.ok) {
                // console.error('任务API请求失败，状态码:', response.status);
                throw new Error(`HTTP错误，状态码: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            // console.log('任务API响应数据:', data);
            if (data.success) {
                if (data.tasks && data.tasks.length > 0) {
                    // console.log('获取到', data.tasks.length, '个任务');
                    
                    // 分页逻辑
                    const pageSize = 2; // 每页显示3条记录
                    const totalTasks = data.tasks.length;
                    const totalPages = Math.ceil(totalTasks / pageSize);
                    
                    // 确保页码在有效范围内
                    const currentPage = Math.max(1, Math.min(page, totalPages));
                    
                    // 计算当前页的任务
                    const startIndex = (currentPage - 1) * pageSize;
                    const endIndex = Math.min(startIndex + pageSize, totalTasks);
                    const currentPageTasks = data.tasks.slice(startIndex, endIndex);
                    
                    // 清空任务列表并添加当前页的任务
                    taskList.innerHTML = '';
                    currentPageTasks.forEach(task => {
                        const taskItem = createTaskItem(task);
                        taskList.appendChild(taskItem); // 添加任务项到任务列表
                    });
                    
                    // 创建分页控件
                    const paginationContainer = document.createElement('div');
                    paginationContainer.className = 'pagination-container';
                    
                    // 添加分页信息
                    const paginationInfo = document.createElement('div');
                    paginationInfo.className = 'pagination-info';
                    paginationInfo.textContent = `第 ${currentPage}/${totalPages} 页，共 ${totalTasks} 条记录`;
                    paginationContainer.appendChild(paginationInfo);
                    
                    // 添加分页按钮
                    const paginationControls = document.createElement('div');
                    paginationControls.className = 'pagination-controls';
                    
                    // 上一页按钮
                    const prevBtn = document.createElement('button');
                    prevBtn.className = 'pagination-btn prev-btn';
                    prevBtn.textContent = '上一页';
                    prevBtn.disabled = currentPage <= 1;
                    prevBtn.addEventListener('click', function() {
                        if (currentPage > 1) {
                            const activeFilter = document.querySelector('.task-list-container .filter-btn.active');
                            const filterStatus = activeFilter ? activeFilter.dataset.status : -1;
                            loadTasks(filterStatus, currentPage - 1);
                        }
                    });
                    paginationControls.appendChild(prevBtn);
                    
                    // 页码按钮
                    const maxPageButtons = 5; // 最多显示5个页码按钮
                    let startPage = Math.max(1, currentPage - Math.floor(maxPageButtons / 2));
                    let endPage = Math.min(totalPages, startPage + maxPageButtons - 1);
                    
                    if (endPage - startPage + 1 < maxPageButtons) {
                        startPage = Math.max(1, endPage - maxPageButtons + 1);
                    }
                    
                    for (let i = startPage; i <= endPage; i++) {
                        const pageBtn = document.createElement('button');
                        pageBtn.className = 'pagination-btn page-btn' + (i === currentPage ? ' active' : '');
                        pageBtn.textContent = i;
                        pageBtn.addEventListener('click', function() {
                            if (i !== currentPage) {
                                const activeFilter = document.querySelector('.task-list-container .filter-btn.active');
                                const filterStatus = activeFilter ? activeFilter.dataset.status : -1;
                                loadTasks(filterStatus, i);
                            }
                        });
                        paginationControls.appendChild(pageBtn);
                    }
                    
                    // 下一页按钮
                    const nextBtn = document.createElement('button');
                    nextBtn.className = 'pagination-btn next-btn';
                    nextBtn.textContent = '下一页';
                    nextBtn.disabled = currentPage >= totalPages;
                    nextBtn.addEventListener('click', function() {
                        if (currentPage < totalPages) {
                            const activeFilter = document.querySelector('.task-list-container .filter-btn.active');
                            const filterStatus = activeFilter ? activeFilter.dataset.status : -1;
                            loadTasks(filterStatus, currentPage + 1);
                        }
                    });
                    paginationControls.appendChild(nextBtn);
                    
                    paginationContainer.appendChild(paginationControls);
                    taskList.appendChild(paginationContainer);
                } else {
                    // console.log('没有找到任务');
                    taskList.innerHTML = '<div class="no-data">暂无任务</div>';
                }
            } else {
                // console.error('加载任务失败:', data.message);
                taskList.innerHTML = `<div class="error-message">${data.message || '加载任务失败'}</div>`;
            }
        })
        .catch(error => {
            // console.error('加载任务出错:', error);
            taskList.innerHTML = `<div class="error-message">加载任务出错: ${error.message}</div>`;
        });
}

// 创建任务项
function createTaskItem(task) {
    const taskItem = document.createElement('div');
    taskItem.className = 'task-item';
    taskItem.dataset.id = task.id;
    
    // 根据任务状态设置不同的样式
    if (task.status === 0) {
        taskItem.classList.add('task-dispatched');
    } else if (task.status === 1) {
        taskItem.classList.add('task-completed');
    } else if (task.status === 2) {
        taskItem.classList.add('task-confirmed');
    }
    
    // 格式化日期
    const createDate = new Date(task.createTime).toLocaleString();
    let completeDate = task.completeTime ? new Date(task.completeTime).toLocaleString() : '未完成';
    let confirmDate = task.confirmTime ? new Date(task.confirmTime).toLocaleString() : '未确认';
    
    // 获取状态文本
    let statusText = '';
    if (task.status === 0) {
        statusText = '派遣中';
    } else if (task.status === 1) {
        statusText = '完成待确认';
    } else if (task.status === 2) {
        statusText = '已完成';
    }
    
    taskItem.innerHTML = `
        <div class="task-header">
            <h4 class="task-title">${task.title}</h4>
            <div class="task-actions">
                <span class="task-status ${task.status === 0 ? 'status-dispatched' : task.status === 1 ? 'status-completed' : 'status-confirmed'}">${statusText}</span>
                ${task.status === 1 ? `<button class="confirm-task-btn" data-id="${task.id}" title="确认完成"><i class="fas fa-check"></i> 确认完成</button>` : ''}
                ${task.status === 2 ? `<button class="edit-score-btn" data-id="${task.id}" title="修改评分"><i class="fas fa-edit"></i> 修改评分</button>` : ''}
                <button class="delete-task-btn" data-id="${task.id}" title="删除任务"><i class="fas fa-trash-alt"></i></button>
            </div>
        </div>
        <div class="task-body">
            <p class="task-content">${task.content}</p>
            <div class="task-info">
                <p><strong>任务ID:</strong> ${task.id}</p>
                <p><strong>员工姓名:</strong> ${task.employeeName || '未知'}</p>
                <p><strong>员工手机:</strong> ${task.employeePhone || '未知'}</p>
                <p><strong>创建时间:</strong> ${createDate}</p>
                ${task.status >= 1 ? `<p><strong>完成时间:</strong> ${completeDate}</p>` : ''}
                ${task.status === 2 ? `<p><strong>确认时间:</strong> ${confirmDate}</p>` : ''}
                ${task.status === 2 ? `<p><strong>评分:</strong> <span class="task-score">${task.score}</span>/10</p>` : ''}
            </div>
        </div>
    `;
    
    // 如果任务状态为"完成待确认"，添加点击事件
    if (task.status === 1) {
        // 添加确认完成按钮事件
        const confirmBtn = taskItem.querySelector('.confirm-task-btn');
        confirmBtn.addEventListener('click', function(e) {
            e.stopPropagation(); // 阻止事件冒泡
            // 默认给7分并确认完成
            confirmTask(task.id, 7, true);
        });
        
        // 保留原来的点击打开模态框功能，用于自定义评分
        const taskBody = taskItem.querySelector('.task-body');
        taskBody.addEventListener('click', function() {
            openTaskConfirmModal(task);
        });
    }
    
    // 如果任务状态为"已完成"，添加修改评分按钮事件
    if (task.status === 2) {
        const editScoreBtn = taskItem.querySelector('.edit-score-btn');
        editScoreBtn.addEventListener('click', function(e) {
            e.stopPropagation(); // 阻止事件冒泡
            openEditScoreModal(task);
        });
    }
    
    // 添加删除按钮事件
    const deleteBtn = taskItem.querySelector('.delete-task-btn');
    deleteBtn.addEventListener('click', function(e) {
        e.stopPropagation(); // 阻止事件冒泡，避免触发父元素的点击事件
        confirmDeleteTask(task.id);
    });
    
    return taskItem;
}

// 确认删除任务
function confirmDeleteTask(taskId) {
    if (confirm('确定要删除这个任务吗？此操作不可恢复。')) {
        deleteTask(taskId);
    }
}

// 删除任务
function deleteTask(taskId) {
    fetch('./api/task/delete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ taskId: taskId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 删除成功，刷新任务列表
            alert(data.message);
            const activeFilter = document.querySelector('.task-list-container .filter-btn.active');
            const currentPage = document.querySelector('.pagination-btn.page-btn.active');
            loadTasks(
                activeFilter ? activeFilter.dataset.status : -1, 
                currentPage ? parseInt(currentPage.textContent) : 1
            );
        } else {
            // 删除失败，显示错误信息
            alert('删除失败: ' + data.message);
        }
    })
    .catch(error => {
        // console.error('删除任务出错:', error);
        alert('删除任务出错: ' + error.message);
    });
}

// 打开任务确认模态框
function openTaskConfirmModal(task) {
    const modal = document.getElementById('task-confirm-modal');
    const content = document.getElementById('task-confirm-content');
    
    // 格式化日期
    const createDate = new Date(task.createTime).toLocaleString();
    const completeDate = new Date(task.completeTime).toLocaleString();
    
    content.innerHTML = `
        <div class="task-detail">
            <h4>${task.title}</h4>
            <p>${task.content}</p>
            <div class="task-info">
                <p><strong>任务ID:</strong> ${task.id}</p>
                <p><strong>创建时间:</strong> ${createDate}</p>
                <p><strong>完成时间:</strong> ${completeDate}</p>
            </div>
        </div>
        <input type="hidden" id="confirm-task-id" value="${task.id}">
    `;
    
    // 重置评分滑块
    document.getElementById('task-score').value = 7;
    document.getElementById('score-value').textContent = '7';
    
    // 添加确认完成按钮事件
    document.getElementById('confirm-complete-btn').onclick = function() {
        const taskId = document.getElementById('confirm-task-id').value;
        const score = parseInt(document.getElementById('task-score').value);
        confirmTask(taskId, score, true);
    };
    
    // 添加未能完成按钮事件
    document.getElementById('mark-incomplete-btn').onclick = function() {
        const taskId = document.getElementById('confirm-task-id').value;
        confirmTask(taskId, 0, false);
    };
    
    modal.style.display = 'block';
}

// 派遣任务
function dispatchTask() {
    const employeeId = document.getElementById('task-employee').value;
    const title = document.getElementById('task-title').value;
    const content = document.getElementById('task-content-input').value;
    
    if (!employeeId) {
        showMessage('请选择员工', 'error');
        return;
    }
    
    if (!title) {
        showMessage('请输入任务标题', 'error');
        return;
    }
    
    if (!content) {
        showMessage('请输入任务内容', 'error');
        return;
    }
    
    const task = {
        title: title,
        content: content,
        employeeId: employeeId
    };
    
    // console.log('发送任务创建请求:', task);
    
    fetch('./api/task/create', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(task)
    })
    .then(response => {
        // console.log('任务创建响应状态:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP错误，状态码: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        // console.log('任务创建响应数据:', data);
        if (data.success) {
            showMessage('任务派遣成功', 'success');
            document.getElementById('task-dispatch-form').reset();
            loadTasks();
        } else {
            showMessage('任务派遣失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        // console.error('任务派遣出错:', error);
        showMessage('任务派遣出错: ' + error.message, 'error');
    });
}

// 确认任务
function confirmTask(taskId, score, isCompleted) {
    // console.log('发送任务确认请求:', { taskId, score, isCompleted });
    
    fetch('./api/task/confirm', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            taskId: taskId,
            score: score,
            isCompleted: isCompleted
        })
    })
    .then(response => {
        // console.log('任务确认响应状态:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP错误，状态码: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        // console.log('任务确认响应数据:', data);
        if (data.success) {
            showMessage(data.message, 'success');
            document.getElementById('task-confirm-modal').style.display = 'none';
            loadTasks();
        } else {
            showMessage('操作失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        // console.error('任务确认出错:', error);
        showMessage('操作出错: ' + error.message, 'error');
    });
}

// 打开修改评分模态框
function openEditScoreModal(task) {
    const modal = document.getElementById('edit-score-modal');
    const content = document.getElementById('edit-score-content');
    
    // 格式化日期
    const createDate = new Date(task.createTime).toLocaleString();
    const completeDate = new Date(task.completeTime).toLocaleString();
    const confirmDate = new Date(task.confirmTime).toLocaleString();
    
    content.innerHTML = `
        <div class="task-detail">
            <h4>${task.title}</h4>
            <p>${task.content}</p>
            <div class="task-info">
                <p><strong>任务ID:</strong> ${task.id}</p>
                <p><strong>员工姓名:</strong> ${task.employeeName || '未知'}</p>
                <p><strong>员工手机:</strong> ${task.employeePhone || '未知'}</p>
                <p><strong>创建时间:</strong> ${createDate}</p>
                <p><strong>完成时间:</strong> ${completeDate}</p>
                <p><strong>确认时间:</strong> ${confirmDate}</p>
                <p><strong>当前评分:</strong> <span class="task-score">${task.score}</span>/10</p>
            </div>
        </div>
        <input type="hidden" id="edit-task-id" value="${task.id}">
    `;
    
    // 设置评分滑块的初始值为当前评分
    document.getElementById('edit-task-score').value = task.score;
    document.getElementById('edit-score-value').textContent = task.score;
    
    // 添加更新评分按钮事件
    document.getElementById('update-score-btn').onclick = function() {
        const taskId = document.getElementById('edit-task-id').value;
        const newScore = parseInt(document.getElementById('edit-task-score').value);
        updateTaskScore(taskId, newScore);
    };
    
    modal.style.display = 'block';
}

// 更新任务评分
function updateTaskScore(taskId, score) {
    // console.log('发送更新评分请求:', { taskId, score });
    
    fetch('./api/task/update-score', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            taskId: taskId,
            score: score
        })
    })
    .then(response => {
        // console.log('更新评分响应状态:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP错误，状态码: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        // console.log('更新评分响应数据:', data);
        if (data.success) {
            showMessage(data.message, 'success');
            document.getElementById('edit-score-modal').style.display = 'none';
            loadTasks();
        } else {
            showMessage('操作失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        // console.error('更新评分出错:', error);
        showMessage('操作出错: ' + error.message, 'error');
    });
}

// 初始化员工绩点查看功能
function initEmployeePerformance() {
    const performanceContent = document.getElementById('performance-content');
    if (!performanceContent) return;
    
    performanceContent.innerHTML = '<div class="loading">加载中...</div>';
    
    // 获取当前年月
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth() + 1; // JavaScript月份从0开始
    
    // 获取员工绩点数据
    loadEmployeePerformanceByYearMonth(currentYear, currentMonth);
}

// 根据年月加载员工绩点数据
function loadEmployeePerformanceByYearMonth(year, month) {
    const performanceContent = document.getElementById('performance-content');
    performanceContent.innerHTML = '<div class="loading">加载中...</div>';
    
    fetch(`api/employee/performance?year=${year}&month=${month}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayEmployeePerformance(data);
            } else {
                // 特殊处理"请先设置打卡和绩点参数"的错误
                if (data.message && data.message.includes("请先设置打卡和绩点参数")) {
                    // 显示创建打卡设置的表单
                    displayPerformanceSettingForm(performanceContent, year, month);
                } else {
                    performanceContent.innerHTML = `<div class="error-message">${data.message}</div>`;
                }
            }
        })
        .catch(error => {
            // console.error('获取员工绩点数据失败:', error);
            performanceContent.innerHTML = '<div class="error-message">获取员工绩点数据失败，请设置打卡设置后刷新</div>';
        });
}

// 显示员工绩点数据
function displayEmployeePerformance(data) {
    const performanceContent = document.getElementById('performance-content');
    const performances = data.performances || [];
    const settings = data.settings;
    const month = data.month;
    const year = data.year;
    const hasRecord = data.hasRecord;
    
    // 获取当前年月
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth() + 1; // JavaScript月份从0开始
    
    // 判断是否是当前月份
    const isCurrentMonth = (year === currentYear && month === currentMonth);
    
    let html = `
        <div class="settings-box">
            <div class="settings-header">
                <h3>${year}年${month}月员工绩点设置</h3>
                <button id="edit-performance-settings-btn" class="btn btn-primary"><i class="fas fa-edit"></i> 修改设置</button>
            </div>
            <div class="settings-content">
                <div class="settings-group">
                    <label>满分打卡累积时长：</label>
                    <span>${settings.maxAttendanceHours} 小时</span>
                </div>
                <div class="settings-group">
                    <label>当月打卡绩点百分比：</label>
                    <span>${settings.attendancePercentage * 100}%</span>
                </div>
                <div class="settings-group">
                    <label>当月任务平均评分百分比：</label>
                    <span>${settings.taskPercentage * 100}%</span>
                </div>
                <div class="settings-group">
                    <label>绩点计算公式：</label>
                    <span>(员工当月打卡时长(不超过${settings.maxAttendanceHours}小时)/${settings.maxAttendanceHours}）*${settings.attendancePercentage}*5+（员工当月任务平均分/10）*${settings.taskPercentage}*5</span>
                </div>
            </div>
        </div>
        
        <div id="edit-performance-settings-form-container" style="display: none;">
            <form id="performance-settings-form" class="standard-form">
                <div class="form-group">
                    <label for="max-attendance-hours">满分打卡累积时长（小时）：</label>
                    <input type="number" id="max-attendance-hours" class="form-control" value="${settings.maxAttendanceHours}" min="1" step="0.5" required>
                </div>
                
                <div class="form-group">
                    <label for="attendance-percentage">当月打卡绩点百分比：</label>
                    <input type="number" id="attendance-percentage" class="form-control" value="${settings.attendancePercentage}" min="0" max="1" step="0.1" required>
                    <small class="form-text text-muted">打卡绩点百分比和任务评分百分比之和必须为1.0</small>
                </div>
                
                <div class="form-group">
                    <label for="task-percentage">当月任务平均评分百分比：</label>
                    <input type="number" id="task-percentage" class="form-control" value="${settings.taskPercentage}" min="0" max="1" step="0.1" required>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">保存设置</button>
                    <button type="button" id="cancel-performance-edit-btn" class="btn btn-secondary">取消</button>
                </div>
            </form>
        </div>
        
        <div class="employee-performance-container">
            <div class="filter-container" style="display: flex; justify-content: space-between; align-items: center;">
                <div class="date-filter" style="display: flex; align-items: center; gap: 10px;">
                    <label for="performance-year">年份：</label>
                    <select id="performance-year" class="form-control" style="width: auto; min-width: 100px;">
                        ${generateYearOptions(year)}
                    </select>
                    
                    <label for="performance-month">月份：</label>
                    <select id="performance-month" class="form-control" style="width: auto; min-width: 100px;">
                        ${generateMonthOptions(month)}
                    </select>
                    
                    <button id="view-performance-btn" class="btn btn-primary" style="min-width: 80px;">查看</button>
                </div>
                
                ${isCurrentMonth ? 
                    `<button id="upload-performance-btn" class="btn btn-success">
                        <i class="fas fa-upload"></i> ${hasRecord ? '更新' : '上传'}当前月份绩点
                    </button>` : ''}
            </div>
            
            <h3>${year}年${month}月员工绩点列表</h3>
            
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>员工编号</th>
                            <th>姓名</th>
                            <th>职位</th>
                            <th>当月打卡时长（小时）</th>
                            <th>当月任务平均评分</th>
                            <th>绩点（满分5.0）</th>
                        </tr>
                    </thead>
                    <tbody>
    `;
    
    if (performances && performances.length > 0) {
        performances.forEach(performance => {
            html += `
                <tr>
                    <td>${performance.employeeNumber}</td>
                    <td>${performance.employeeName}</td>
                    <td>${performance.position || '未设置'}</td>
                    <td>${performance.attendanceHours.toFixed(1)}</td>
                    <td>${performance.avgTaskScore.toFixed(1)}</td>
                    <td><strong>${performance.performance}</strong></td>
                </tr>
            `;
        });
    } else {
        html += '<tr><td colspan="6" class="text-center">暂无员工绩点数据</td></tr>';
    }
    
    html += `
                    </tbody>
                </table>
            </div>
        </div>
    `;
    
    performanceContent.innerHTML = html;
    
    // 添加修改按钮点击事件
    document.getElementById('edit-performance-settings-btn').addEventListener('click', function() {
        document.getElementById('edit-performance-settings-form-container').style.display = 'block';
    });
    
    // 添加取消按钮点击事件
    document.getElementById('cancel-performance-edit-btn').addEventListener('click', function() {
        document.getElementById('edit-performance-settings-form-container').style.display = 'none';
    });
    
    // 添加表单提交事件
    document.getElementById('performance-settings-form').addEventListener('submit', function(event) {
        event.preventDefault();
        savePerformanceSettings();
    });
    
    // 添加百分比自动计算功能
    const attendancePercentageInput = document.getElementById('attendance-percentage');
    const taskPercentageInput = document.getElementById('task-percentage');
    
    attendancePercentageInput.addEventListener('input', function() {
        const attendancePercentage = parseFloat(this.value) || 0;
        taskPercentageInput.value = (1 - attendancePercentage).toFixed(1);
    });
    
    taskPercentageInput.addEventListener('input', function() {
        const taskPercentage = parseFloat(this.value) || 0;
        attendancePercentageInput.value = (1 - taskPercentage).toFixed(1);
    });
    
    // 添加查看按钮点击事件
    document.getElementById('view-performance-btn').addEventListener('click', function() {
        const selectedYear = document.getElementById('performance-year').value;
        const selectedMonth = document.getElementById('performance-month').value;
        loadEmployeePerformanceByYearMonth(selectedYear, selectedMonth);
    });
    
    // 添加上传按钮点击事件（如果是当前月份）
    if (isCurrentMonth) {
        document.getElementById('upload-performance-btn').addEventListener('click', function() {
            uploadPerformance(year, month);
        });
    }
}

// 生成年份选项
function generateYearOptions(selectedYear) {
    const currentYear = new Date().getFullYear();
    let options = '';
    
    // 生成从当前年份往前5年的选项
    for (let year = currentYear; year >= currentYear - 5; year--) {
        options += `<option value="${year}" ${year == selectedYear ? 'selected' : ''}>${year}年</option>`;
    }
    
    return options;
}

// 生成月份选项
function generateMonthOptions(selectedMonth) {
    let options = '';
    
    // 生成1-12月的选项
    for (let month = 1; month <= 12; month++) {
        options += `<option value="${month}" ${month == selectedMonth ? 'selected' : ''}>${month}月</option>`;
    }
    
    return options;
}

// 上传员工绩点
function uploadPerformance(year, month) {
    if (!confirm(`确定要${document.getElementById('upload-performance-btn').innerText.includes('更新') ? '更新' : '上传'}${year}年${month}月的员工绩点记录吗？`)) {
        return;
    }
    
    // 显示上传中的提示
    const uploadBtn = document.getElementById('upload-performance-btn');
    const originalText = uploadBtn.innerHTML;
    uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
    uploadBtn.disabled = true;
    
    fetch('api/employee/performance', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            year: year,
            month: month
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            // 重新加载绩点数据
            loadEmployeePerformanceByYearMonth(year, month);
        } else {
            alert('上传失败：' + data.message);
            // 恢复按钮状态
            uploadBtn.innerHTML = originalText;
            uploadBtn.disabled = false;
        }
    })
    .catch(error => {
        // console.error('上传绩点数据失败:', error);
        alert('上传绩点数据失败，请稍后重试');
        // 恢复按钮状态
        uploadBtn.innerHTML = originalText;
        uploadBtn.disabled = false;
    });
}

// 保存绩点设置
function savePerformanceSettings() {
    const companyId = getCurrentCompanyId();
    const maxAttendanceHours = parseFloat(document.getElementById('max-attendance-hours').value);
    const attendancePercentage = parseFloat(document.getElementById('attendance-percentage').value);
    const taskPercentage = parseFloat(document.getElementById('task-percentage').value);
    
    // 验证数据
    if (isNaN(maxAttendanceHours) || isNaN(attendancePercentage) || isNaN(taskPercentage)) {
        alert('请输入有效的数值');
        return;
    }
    
    if (Math.abs(attendancePercentage + taskPercentage - 1.0) > 0.001) {
        alert('打卡绩点百分比和任务评分百分比之和必须为1.0');
        return;
    }
    
    // 获取当前打卡设置
    fetch(`api/attendance/setting?companyId=${companyId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const setting = data.data;
                
                // 发送更新请求
                fetch('api/attendance/setting', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        companyId: companyId,
                        checkInStartTime: setting.checkInStartTime,
                        checkInEndTime: setting.checkInEndTime,
                        checkOutStartTime: setting.checkOutStartTime,
                        checkOutEndTime: setting.checkOutEndTime,
                        maxAttendanceHours: maxAttendanceHours,
                        attendancePercentage: attendancePercentage,
                        taskPercentage: taskPercentage
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('绩点设置保存成功');
                        document.getElementById('edit-performance-settings-form-container').style.display = 'none';
                        
                        // 获取当前选择的年月并重新加载绩点数据
                        const selectedYear = document.getElementById('performance-year').value;
                        const selectedMonth = document.getElementById('performance-month').value;
                        loadEmployeePerformanceByYearMonth(selectedYear, selectedMonth);
                    } else {
                        alert('绩点设置保存失败：' + data.message);
                    }
                })
                .catch(error => {
                    // console.error('保存绩点设置失败:', error);
                    alert('保存绩点设置失败，请稍后重试');
                });
            } else {
                alert('获取当前打卡设置失败：' + data.message);
            }
        })
        .catch(error => {
            // console.error('获取当前打卡设置失败:', error);
            alert('获取当前打卡设置失败，请稍后重试');
        });
} 